Posted on 10-10-2008
Filed Under (inglês, ruby on rails) by ontonho

There are many good plugins to upload files in Rails, but it is possile to do it by a simple way. I will show it step by step.

1- Create a Rails project

>> rails photos
>> cd photos

2- Create a folder inside Public (or another place you want) where the music will be.

>> mkdir public/photos

3- Generate model Photo

>> script/generate model photo

4- Edit model with a content bellow:

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

5- Generate the photo contoller

>> script/generate controller Photo

6- Edit controller with a content bellow:

def index
     render :file => 'app\views\upload\uploadfile.rhtml'
  end
  def create
    post = Music.save(params[:upload])
    render :text => "File has been uploaded successfully"
  end

7- Create a view (uploadfile.rhtml)

<h1>File Upload</h1>
<% form_for( :html => { :multipart => true }, :action => :create) do |f| %>
<p><%= file_field 'upload', 'datafile' %></p>
  <p><%= f.submit "Create" %></p>
<% end %>

8- open browser, upload a file and verify public/photos

    Read More   
Post a Comment
Name:
Email:
Website:
Comments: