繁体   English   中英

使用ruby / rails将文件上传到网站

[英]uploading a file to a website with 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 %>

我认为代码几乎是自我解释的,所以我不会解释它;

Paperclip gem确实是一种解决方案。 它也适用于其他格式,并且很容易在rails中实现。 看看视频.. !!

http://railscasts.com/episodes/134-paperclip

您可能想查看Paperclip插件。 非常适合上传图片。 也可能适用于其他格式。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM