我正在构建一个 Rails 应用程序来测试我们的旗舰产品(也是基于 Web 的)。问题是部分测试需要使用生产应用程序的 Web 界面来上传文件。所以我需要做的是让 rails 应用程序将这些文件上传到生产应用程序(而不是 rails)。有没有办法让 Rails 将文件发布到生产应用程序(就像浏览器将文件发布到生产应用程序一样)?
Josh Moore
问问题
5301 次
4 回答
7
If you just need to upload files, I think it's pointless to use a plugin for this. File upload is very, very simple.
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
Then, your form can look like this:
<% form_for @upload, :multipart => true do |f| %>
<%= f.file_field :uploaded_file %>
<%= f.submit "Upload file" %>
<% end %>
I think the code is pretty much self explanatory, so I won't explain it ; )
于 2008-12-25T10:27:06.870 回答
4
当然,使用 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/
看看这个类似的问题
于 2008-12-24T08:05:13.180 回答
0
您可能想查看 Paperclip 插件。非常适合上传图片。也可能适用于其他格式。
于 2008-12-24T14:38:43.570 回答
0
Paperclip gem 确实是一个解决方案。它也适用于其他格式,并且很容易在 Rails 中实现。看视频..!!
于 2013-06-19T11:46:51.623 回答