Skip to main content
Home
Live to Learn!

Main navigation

  • Home
  • Learn
    • FoxPro
    • MS-DOS
    • C PRG
    • Java
    • ASP
    • Ruby on Rails
    • ASP.NET
    • E-Books
    • Exam Preparation
    • Tools
  • Blog
  • Forums
  • Contact
User account menu
  • Log in

Breadcrumb

  1. Home
  2. Ruby and Rails

File Uploads in Ruby on Rails

Book navigation

  • Single line swapping in Ruby
  • Array Operations in Ruby
  • File operations in Ruby
  • User defined functions in Ruby
  • Classes and Objects in Ruby
  • Simple Form Hello Rails Application
  • Database Application using scaffold - [Video]
  • Session Management
  • Cookies Management in Ruby on Rails
  • File Uploads in Ruby on Rails
By Karthikeyan , 25 October, 2012

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 %>
  • Add new comment

Comments

Featured Blog Posts

Convert Currency in Number to Words (Indian Rupees) - MS Excel
Foxpro Tutorial and Programs
Convert Currency in Number to Words in MS Word
Convert Currency in Number to Words (Indian Rupees) - Version 2
Best way to Use Rupee Symbol in Windows – Easy steps
Convert Currency in Number to Words - MS Access
Creating All in One Windows XP DVD with all Important Applications
RSS feed

© 2009-2025 Live to Learn.In

Terms of Use | Privacy Policy