Jos*_*ore 3 ruby upload ruby-on-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
Run Code Online (Sandbox Code Playgroud)
然后,您的表单可能如下所示:
<% form_for @upload, :multipart => true do |f| %>
<%= f.file_field :uploaded_file %>
<%= f.submit "Upload file" %>
<% end %>
Run Code Online (Sandbox Code Playgroud)
我认为代码几乎是自我解释的,所以我不会解释它; )
| 归档时间: |
|
| 查看次数: |
5090 次 |
| 最近记录: |