将文件上传到另一个Rails应用程序的最佳方法是什么?

时间:2009-06-25 21:03:36

标签: ruby-on-rails ruby activeresource attachment-fu

我研究过并注意到ActiveResource缺乏此功能。那么,在进行文件上传时,当前的技术水平是什么?

Guillermo方法的一个问题是请求必须嵌套,如下所示:

body = { :file => {:uploaded_data => File.open("#{RAILS_ROOT}/public/tmp/" + original_filename), :owner_id => current_user.owner_id }, :api_key => '123123123123123123'}

当然不可能使用HttpClient做这样的请求。我尝试了在github(sevenwire-http-client和technoweenie-rest-client)中找到的其他宝石,但是他们遇到了嵌套文件的问题。是否可以上传带有嵌套请求的文件?

2 个答案:

答案 0 :(得分:3)

Httpclient gem允许你做这样的多部分帖子:

clnt = HTTPClient.new
File.open('/tmp/post_data') do |file|
   body = { 'upload' => file, 'user' => 'nahi' }
   res = clnt.post(uri, body)
 end

您可以使用它将本地文件系统上的文件简单地发布到另一个应用程序中的控制器。如果您想上传数据只需将表格上传到您的应用中而不先存储,您可以立即在帖子正文中使用params上传的数据。

答案 1 :(得分:1)

您可以尝试以下内容:

#I used the HTTPClient gem as suggested (thanks!)
clnt = HTTPClient.new

# The file to be uploaded is originally on /tmp/ with a filename 'RackMultipart0123456789'. 
# I had to rename this file, or the resulting uploaded file will keep that filename. 
# Thus, I copied the file to public/tmp and renamed it to its original_filename.(it will be deleted later on)
original_filename =  params[:message][:file].original_filename
directory = "#{RAILS_ROOT}/public/temporary"
path = File.join(directory, original_filename)
File.open(path, "w+") { |f| f.write(params[:job_application][:resume].read) }

# I upload the file that is currently on public/tmp and then do the post.
body = { :uploaded_data => File.open("#{RAILS_ROOT}/public/tmp/" + original_filename), :owner_id => current_user.owner_id}   
res = clnt.post('http://localhost:3000/files.xml', body)