File Uploads in Ruby on Rails

Submitted by Karthikeyan on

Simple File Upload Application in Ruby on Rails.
This program uploads any type of file to the uploads directory under public folder and stores the file name in database.

Procedure :-

  1. Create database fileuploads through mysql command line or phpmyadmin or Netbeans Services Tab
  2. Create new project and provide the database information
  3. Generate scaffold Upload with argument filename:string
  4. Change the code for Model upload.rb as given below
  5. Change the code for views/uploads/new.html.erb as given below
  6. Delete Public\index.html
  7. Create folder 'Uploads' under Public folder
  8. Edit the Configuration\routes.rb to point uploads controller. map.root :controller => "uploads"
  9. Migrate Database
  10. Execute the application

Model : Upload


class Upload < ActiveRecord::Base
   UPLOAD_STORE = File.join RAILS_ROOT, 'public','Uploads'
  after_save:save_upload
  def load_photo_file=(data)
    self.filename=data.original_filename
    @upload_data=data
  end
  def save_upload
    if @upload_data
      name=File.join UPLOAD_STORE, self.filename
      File.open(name,'wb')do |f|
        f.write(@upload_data.read)
      end
      @upload_data=nil
    end
  end
end

Views : new.html.erb


<h1>New upload</h1>
<% form_for(:upload,@upload, :url => {:action=>'create'}, :html=>{:multipart=>true}) do |f| %>
  <%= f.error_messages %>
  <p>
    <%= f.label "Open File" %><br />
    <%= f.file_field :load_photo_file  %>
  </p>
  <p>
    <%= f.submit 'Upload' %>
  </p>
<% end %>
<%= link_to 'Back', uploads_path %>