Thursday, August 09, 2007

[RoR] File Upload with file_column plugin

Several RoR plugins exist for File Uopload. The more celeb are:




These two plugins can be combined to ImageMagick , when you need to do some operations on an uploaded image (resize, crop).


In this article , i will first speak about file_column.


Download


Install file_column plugin in your RoR application with this command:


./script/plugin install http://opensvn.csie.org/rails_file_column/plugins/file_column/trunk



Create a table, with a column "image" for the file information


Launch the following command to create model class and migration script


script/generate model TestUpload



Modify the migration script:


class AddTable < ActiveRecord::Migration

def self.up

create_table :test_uploads do |t|

t.column :title, :string

t.column :description, :string

t.column :image, :string

end

end




Modify the model class



class TestUpload < ActiveRecord::Base

file_column :image

end




Modify the view (Upload)




<% form_tag ({:action => 'create' }, :multipart => true) do %>

<fieldset>

<legend>Test upload
</legend>

<%= error_messages_for 'test_upload' %>
<br/>

<div id="test_upload" class="form">

<table border=0>

<tr>

<td align="right">

<label for="test_upload_titre">Title:
</label>
<br/>

</td>

<td>

<%= text_field "test_upload", "title", :size => 30 %>

</td>

</tr>

<tr>

<td align="right">

<label for="test_upload_description">Description:
</label>
<br/>

</td>

<td>

<%= text_field "test_upload", "description", :size => 30 %>

</td>

</tr>

<tr>

<td align="right">

<label for="test_upload_image">Upload image:
</label>
<br/>

</td>

<td>

<%= file_column_field "test_upload", "image" %>

</td>

</tr>

<tr>

<td colspan=2>

<input type="submit" value="Send" />

</td>

</tr>

</table>

</div>

</fieldset>

<% end %>



Save the record


In your controller , add the following action:


def create

#

test = TestUpload.create(:titre => params[:test_upload][:title], :description => params[:test_upload][:description], :image => params[:test_upload][:image])<


end




The uploaded file is saved in the folder :


public/:model/:column/:id/filename

Display the uploaded image



<%= image_tag url_for_file_column("test_upload", "image"), :border => 0 %>



Resize images with RMagick


Modify the model class:


class TestUpload < ActiveRecord::Base

file_column :image, :magick => {

:versions => { "thumb" =>
"50x50", "medium" => "640x480>" }

}

end




And diplay the thumb image as :


<%= image_tag url_for_file_column("test_upload", "image", "thumb"), :border => 0 %>

Labels:

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home