本文介绍了Ruby on Rails的:REST API +文件上传+回形针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想通过一个PUT请求上传使用REST API我的服务器上的附件。我可以把二进制文件中请求主体做到这一点,但我也想保存此文件作为附件到使用回形针保存附件的典范。
I'm trying to upload an attachment using REST API on my server through a PUT request. I can do this by putting the binary file in the request body but I'd also like to save this file as an attachment to a model which uses paperclip to save attachments.
下面是我目前参与的类定义:
Here's my current involved class definitions:
class Cl < ActiveRecord::Base
after_update :save_tses
validates_associated :tses
has_many :tses
...truncated...
def save_tses
tses.each do |ts|
ts.save(false)
end
end
end
class Ts < ActiveRecord::Base
has_attached_file :tsa, :styles => { :thumb => {:geometry => "100x141>", :format => :jpg} },
:path => ":rails_root/public/system/:attachment/:id/:style/:friendly_filename",
:url => "/system/:attachment/:id/:style/:friendly_filename"
belongs_to :cl
def friendly_filename
"#{self.tsa_file_name.gsub( /[^a-zA-Z0-9_\.]/, '_')}"
end
end
我就好使用HTML页面上的文件上传保存附件。我想做到这一点,通过PUT请求接收文件作为二进制数据控制器上。
I can save the attachments just fine using the file upload on the html page. I'd like to do this on a controller that receives the file as binary data through a PUT request.
有什么建议?
推荐答案
明白了,
# controller.rb
def add_ts
# params[:id]
# params[:tsa]
@cl = Cl.find(params[:id])
ts = @cl.tses.build(:name => "#{@cl.name}_#{Time.now.to_i}")
ts.tsa = params[:tsa]
if ts.save
render :json => {:status => "OK"}
else
render :json => {:status => "ERROR"}
end
end
# Test
curl -F "[email protected]" "http://host/cl/474/add_ts"
=> {"status":"OK"}
这篇关于Ruby on Rails的:REST API +文件上传+回形针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!