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 :-
- Create database fileuploads through mysql command line or phpmyadmin or Netbeans Services Tab
- Create new project and provide the database information
- Generate scaffold
Upload
with argumentfilename:string
- Change the code for Model upload.rb as given below
- Change the code for views/uploads/new.html.erb as given below
- Delete Public\index.html
- Create folder 'Uploads' under Public folder
- Edit the Configuration\routes.rb to point uploads controller.
map.root :controller => "uploads"
- Migrate Database
- 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 %>