uploading a file to a website with ruby/rails

纵饮孤独 提交于 2019-11-30 10:24:10

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

diclophis

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?

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

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!