Recipe 15.3. Serving Images Directly from a Database


Problem

You're storing images in a database as binary data, and you want to display the images in a browser.

Solution

Add a method to your controller for displaying a stored image, based on an incoming ID parameter:

app/controllers/photos_controller.rb:

class PhotosController < ApplicationController   def show     @photo = Photo.find(params[:id])      send_data(@photo.data,                 :filename => @photo.name,                 :type => @photo.content_type,                 :disposition => "inline")  end end

Now, add an image tag to your view (show.rhtml, in this case) with a source consisting of the following call to url_for:

views/items/show.rhtml:

<% for column in Item.content_columns %> <p>   <b><%= column.human_name %>:</b> <%=h @item.send(column.name) %> </p> <% end %> <img src="/books/4/185/1/html/2/<%= url_for(:controller => "photos",                        :action => "show",                        :id => @photo.id) %>" /> ; <%= link_to 'Edit', :action => 'edit', :id => @item %> | <%= link_to 'Back', :action => 'list' %>

Discussion

For a browser to display binary image data, it needs to be instructed that the data is an image. Specifically, it needs to be told that the content type of the data is something like image/gif. Providing a filename gives the browser something to name the data, should it be downloaded and saved by the user. Finally, the disposition specifies whether the file will be displayed inline or downloaded as an attachment. If its disposition is not specified, it's assumed to be an attachment.

In the solution, the photo object's binary data (the actual image) is passed to the call to send_data, along with the filename given by the object's name attribute. The symbol :disposition => 'inline' specifies that the image is to be displayed inline with the rest of the HTML output.

See Also

  • Section 15.2"




Rails Cookbook
Rails Cookbook (Cookbooks (OReilly))
ISBN: 0596527314
EAN: 2147483647
Year: 2007
Pages: 250
Authors: Rob Orsini

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net