简体   繁体   中英

uploading a file to a website with ruby/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 ; )

Sure, use the net/http library...

http://www.ruby-doc.org/stdlib/libdoc/net/http/rdoc/classes/Net/HTTP.html

but it would appear that it is missing multipart encoding, so check out this other article

http://kfahlgren.com/blog/2006/11/01/multipart-post-in-ruby-2/

Check out this similar question

Ruby: How to post a file via HTTP as multipart/form-data?

Paperclip gem is indeed a solution. It works on other formats too and its very easy to implement in rails. Check out the video..!!

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

You might wanna check out the Paperclip plugin. Very good for uploading images. Might work for other formats too.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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