uploading a file to a website with ruby/rails

前端 未结 4 1360
庸人自扰
庸人自扰 2021-01-01 07:36

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 uploa

相关标签:
4条回答
  • 2021-01-01 08:02

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

    0 讨论(0)
  • 2021-01-01 08:12

    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

    0 讨论(0)
  • 2021-01-01 08:25

    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 ; )

    0 讨论(0)
  • 2021-01-01 08:29

    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?

    0 讨论(0)
提交回复
热议问题