1

我研究并注意到 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 中找到的其他 gem(sevenwire-http-client 和 technoweenie-rest-client),但它们在嵌套文件时遇到了问题。是否可以上传带有嵌套请求的文件?

4

2 回答 2

3

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

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

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

于 2009-06-26T00:14:30.700 回答
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)
于 2009-07-08T20:29:45.703 回答