I wanted to do something similar. My app has a thumbnail image and
“full”
image for each user, and I store them in the DB as a blob. I want to
return
them to the client through an URL (that is, other parts of my app can
just
put in the correct URL, without having to know much about how the images
are
stored or generated.)
Additionally, I wanted to to let the user upload various kinds of images
(JPEG, GIF, etc.), and I wanted the URLs to look “right” (e.g. have the
right extension, etc.)
Here’s the code I wrote to return images (in my User controller):
def image
#MES- Need security here?
@user = User.find(params[:id])
send_image(@user.image)
end
def thumbnail
#MES- Need security here?
@user = User.find(params[:id])
send_image(@user.thumbnail)
end
def send_image(img)
send_data(img.data, :filename => img.name http://img.name, :type =>
img.content_type, :disposition => ‘inline’)
end
The @user.image and @user.thumbnail members are basically the Picture
class
from the Agile book, with some small additions for turning full sized
images
into thumbnails, etc.
To make the URL for a thumbnail, I use code like this
image_tag(url_for(:controller => ‘user’, :action => ‘thumbnail’, :id =>
“#{
user.id http://user.id}#{user.thumbnail.extension}”))
and then in my routes, I map all extensions to the same method (e.g. a
request to /user/image/123.gif will call UserController::image with ID
123):
#MES- Map any file extension for user ‘image’ or ‘thumbnail’ to the
action
map.connect ‘user/image/:id’, :controller => ‘user’, :action => ‘image’,
:id
=> /^...$/
map.connect ‘user/thumbnail/:id’, :controller => ‘user’, :action =>
‘thumbnail’, :id => /^...$/