Uploading a file to a site with rubies / rails

I am creating a rails application to test our flagship product (also based on the Internet). The problem is that partial testing requires using the web interface of the production application to download files. Therefore, I need to have the rails application load these files into the production application (and not the rails). Is there a way for the rails to send the file to the production application (for example, the browser sends the file to the production application)?

+3
source share
4 answers

If you just need to upload files, I think it makes no sense to use a plugin for this. Downloading a file 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 might look like this:

<% form_for @upload, :multipart => true do |f| %>
  <%= f.file_field :uploaded_file %>
  <%= f.submit "Upload file" %>
<% end %>

I think the code pretty much explains itself, so I won't explain it; )

+7
source

Of course, use the net / http library ...

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

but it doesn't seem to have multi-page 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 send a file via HTTP as multipart / form-data?

+4
source

, Paperclip. . .

0

A gem of a paper clip is really a solution. It also works with other formats, and it is very easy to implement in rails. Watch the video..!!

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

0
source

All Articles