使用ruby / rails将文件上传到网站
我正在构建一个rails应用程序来测试我们的旗舰产品(也是基于Web的)。 问题是部分测试需要使用生产应用程序的Web界面来上传文件。 所以我需要做的是让rails app将这些文件上传到生产应用程序(而不是rails)。 有没有办法让rails将文件发布到生产应用程序(比如浏览器将文件发布到生产应用程序)?
如果你只需要上传文件,我认为使用插件是没有意义的。 文件上传非常非常简单。
class Upload < ActiveRecord::Base before_create :set_filename after_create :store_file after_destroy :delete_file validates_presence_of :uploaded_file attr_accessor :uploaded_file def link "/uploads/#{CGI.escape(filename)}" end private def store_file File.open(file_storage_location, 'w') do |f| f.write uploaded_file.read end end def delete_file File.delete(file_storage_location) end def file_storage_location File.join(Rails.root, 'public', 'uploads', filename) end def set_filename self.filename = random_prefix + uploaded_file.original_filename end def random_prefix Digest::SHA1.hexdigest(Time.now.to_s.split(//).sort_by {rand}.join) end end
然后,您的表单可能如下所示:
<% form_for @upload, :multipart => true do |f| %> <%= f.file_field :uploaded_file %> <%= f.submit "Upload file" %> <% end %>
我认为代码几乎是自我解释的,所以我不会解释它; )
当然,使用net / http库…
http://www.ruby-doc.org/stdlib/libdoc/net/http/rdoc/classes/Net/HTTP.html
但它似乎缺少多部分编码,所以看看这篇文章
http://kfahlgren.com/blog/2006/11/01/multipart-post-in-ruby-2/
看看这个类似的问题
Ruby:如何通过HTTP将文件作为multipart / form-data发布?
您可能想查看Paperclip插件。 非常适合上传图片。 也可能适用于其他格式。
Paperclip gem确实是一种解决方案。 它也适用于其他格式,并且很容易在rails中实现。 看看video.. !!