Tuesday, May 25, 2010

Rails Upload

Today only very few applications are there which does not require any kinds file uploading.

So I came up with easy file uploading in Ruby on Rails.
let's start off with a new Rails application called upload. So let's create basic structure of the application by using simple rails command.

C:\ruby> rails upload

Now do this
C:\ruby> cd upload
C:\ruby> mkdir upload\public\data

Now creating controller and models,

Creating Model:


C:\ruby> ruby script/generate model DataFile
exists app/models/
exists test/unit/
exists test/fixtures/
create app/models/data_file.rb
create test/unit/data_file_test.rb
create test/fixtures/data_files.yml
create db/migrate


create a method called save in data_file.rb model file.

class DataFile < ActiveRecord::Base
def self.save(upload)
name = upload['datafile'].original_filename
directory = "public/data"
# create the file path
path = File.join(directory, name)
# write the file
File.open(path, "wb") { |f| f.write(upload['datafile'].read) }
end
end


Creating Controller:


C:\ruby> ruby script/generate controller Upload
exists app/controllers/
exists app/helpers/
create app/views/upload
exists test/functional/
create app/controllers/upload_controller.rb
create test/functional/upload_controller_test.rb




Now we will create two controller functions first function index will call a view file to take user input and second function uploadFile takes file information from the user and passes it to the 'DataFile' model. We set the upload directory to the 'uploads' directory we created earlier "directory = 'data'".

class UploadController < ApplicationController
def index
render :file => 'app\views\upload\uploadfile.rhtml'
end
def uploadFile
post = DataFile.save(params[:upload])
render :text => "File has been uploaded successfully"
end
end

Here we are calling function defined in model file. The render function is being used to redirect to view file as well as to display a message.

Creating View:

Finally we will create a view file uploadfile.rhtml which we have mentioned in controller. Populate this file with the following code:

File Upload


<%= start_form_tag ({:action => 'uploadFile'},
:multipart => true) %>

:
<%= file_field 'upload', 'datafile' %>


<%= submit_tag "Upload" %>
<%= end_form_tag %>

Here everything is same what we have explained in earlier chapters. Only new tag is file_field which will create a button to select a file from user's computer.

By setting the multipart parameter to true, you ensure that your action properly passes along the binary data from the file.


create app/helpers/upload_helper.rb
This method will be called by the application controller.
create db/migrate/001_create_data_files.rb


Script is ready to serve just run Ruby script/server

and then go to http://localhost:3000/upload/index



Thanks hope every thing works fine. If any problem I will be there to help you.