Search This Blog

Monday, April 4, 2011

Rails : saving and displaying images from database


Here is the logic to save images into blob and displaying those saved images..

Here is my database table:

| Field | Type
----------------------------------------------------------
| id | int(11)
| upload_file_name | varchar(255)
| upload_content_type | varchar(255)
| upload_file_size | int(11)
| created_at | datetime
| updated_at | datetime
| data | mediumblob
-----------------------------------------------------------

In VIEW:

<%= f.file_field :image_file, :value => "Select a file"%>

In CONTROLLER:

@uploadimages = UploadImage.new
@uploadimages.upload_file_name = params[:image_attributes][:image_file2].original_filename
@uploadimages.upload_content_type = params[:image_attributes][:image_file2].content_type
@uploadimages.upload_file_size = params[:image_attributes][:image_file2].size
@uploadimages.data = params[:image_attributes][:image_file2].read
@uploadimages.save

This will save the image into the database.

-------------------------------

Here is the code to display the saved image from the database:

In CONTROLLER:

def show_image
@image = UploadImage.find(params[:id])
send_data @image.data, :type => 'image/png', :disposition => 'inline'
end

In VIEW:

<%= image_tag url_for(:action => 'show_image', :id => images.id), :size => "300x200") %>


This will display the image!!

2 comments:

  1. That is not a blob type. It only save in one folder directory in your project path.

    ReplyDelete