Wednesday, February 11, 2009

File upload in rails


Follow the steps
Go to terminal and type
rails upload
then
cd upload
mkdir upload\public\data
ruby script/generate model DataFile

Then in data_file.rb
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


Then again in terminal
ruby script/generate controller Upload

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


uploadFile.rhtml

File Upload


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

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


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


Reference link:http://www.tutorialspoint.com/ruby-on-rails/rails-file-uploading.htm

9 comments:

TechSlam said...

NoMethodError in Upload#index

Showing app/views/upload/uploadfile.rhtml where line #3 raised:

undefined method `start_form_tag' for ActionView::Base:0x491595c

TechSlam said...

Have you tested this code before posting......?????

allen said...

he copied the code straight from the linked page. 'start_form_tag' is deprecated now. use 'form_tag'....

Anna said...

This worked for me when I took out the render command in the controller, and instead replaced it with a more standard respond_to do loop: " respond_to do |format|
format.html # index.html.erb
end
"

Unknown said...

So what's the correct code? I've tried several variatio unfortunately without success. Can someone post the address to write code or a link where you can find them? Schumi

Unknown said...

hey,Code Doesn't works like copied the code from somewhere.
Please check the code before posting.

Mukund

Sanjeev Kumar Mishra said...
This comment has been removed by the author.
shaik abdul hafeez said...

hi viewers

it worked for me

Angelo Azevedo said...

I'm new on rails, so it didn't work here, but Idk why