【问题标题】:What is the best way to upload a file to another Rails application?将文件上传到另一个 Rails 应用程序的最佳方式是什么?
【发布时间】:2009-06-25 21:03:36
【问题描述】:

我研究并注意到 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),但是它们在嵌套文件时遇到了问题。是否可以上传带有嵌套请求的文件?

【问题讨论】:

  • 如果你知道已经有一个关于这个的问题,为什么还要问另一个?
  • 因为这不是一个已解决的问题。只是一些建议。
  • 对于类似的任务,我通常使用 mechanize 编写 ruby​​ 脚本 - 请参阅 mechanize.rubyforge.org/mechanize

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


【解决方案1】:

Httpclient gem 允许您像这样发布多部分帖子:

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

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

【讨论】:

  • 感谢您的评论。我想对此进行一些讨论,但似乎几乎没有人感兴趣:(
  • 安装 HTTPClient gem 后出现此错误。 NameError(未初始化的常量 ClientDocumentsController::HTTPClient):在这一行上 clnt = HTTPClient.new
【解决方案2】:

您可以尝试以下方法:

#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)

【讨论】:

  • @Guillermmo 安装 HTTPClient gem 后,我收到此错误。 NameError(未初始化的常量 ClientDocumentsController::HTTPClient):在这一行上 clnt = HTTPClient.new
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-01-27
  • 2013-05-20
  • 2010-09-20
  • 2010-09-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多