问题描述
我正在构建一个 rails 应用程序来测试我们的旗舰产品(也是基于网络的).问题是部分测试需要使用生产应用程序的 Web 界面上传文件.所以我需要做的是让 rails 应用程序将这些文件上传到生产应用程序(不是 rails).有没有办法让 rails 将文件发布到生产应用程序(就像浏览器将文件发布到生产应用程序一样)?
I am building a rails app to test our flagship product (also web based). The problem is that part of the testing requires using the production app's web interface to upload files. So what i need to do is have the rails app upload these files to the production application (not rails). Is there a way to have rails post the file to the production application (like the browser posts the file to the production app)?
推荐答案
如果你只是需要上传文件,我认为使用插件是没有意义的.文件上传非常非常简单.
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 ; )
这篇关于使用 ruby/rails 将文件上传到网站的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!