Serving Images Stored in the Database with Rails

April 19, 2008

Some Rails applications accept images uploaded by users via the application, such as profile images. You have a few choices as to how to store the image. I'm not going to go over them or debate the merits of each in this article. Instead I'm going to cover how to handle it if you've decided that you want to store your images in the database.

So to get started with the example, create a rails app and an image model to hold the image data:

$ rails myapp
$ cd myapp
$ script/generate model image file_name:string content_type:string \
file_size:integer file_data:binary
$ rake db:migrate

Ok, now let's put the awesomest image ever into our database:

$ script/console 

>> require 'net/http'
=> []

>> host = 'farm1.static.flickr.com'
=> "farm1.static.flickr.com"

>> path = '/62/163977533_55fd5ddd9b_o_d.jpg'
=> "/62/163977533_55fd5ddd9b_o_d.jpg"

>> res = Net::HTTP.get_response(host, path)
=> #<Net::HTTPOK 200 OK readbody=true>

>> Image.create!(:file_name => "awesome.jpg", 
  :content_type => res['Content-type'], 
  :file_size => res.body.size, 
  :file_data => res.body)
=> #<Image id: 1, file_name: "awesome.jpg"...

I've added some spacing for dramatic effect. Now, create an images controller at app/controllers/images_controller.rb:

class ImagesController < ApplicationController
  caches_page :show
  def show
    if @image = Image.find_by_file_name(params[:file_name])
      send_data(
        @image.file_data, 
        :type => @image.content_type,
        :filename => @image.file_name,
        :disposition => 'inline'
      )
    else
      render :file => "#{RAILS_ROOT}/public/404.html", :status => 404
    end
  end
end

Then setup a route:

map.connect "/images/*file_name", :controller => "images", :action => "show"

Next make sure caching is turned on for your development environment. Edit this line in config/environments/development.rb:

config.action_controller.perform_caching = true

And finally, start up rails and view the image in your browser at http://localhost:3000/images/awesome.jpg. If you look in your log, you will see a line like this:

Cached page: /images/awesome.jpg (0.00100)

But if you refresh your browser or hit the same URL from a different browser, you will not see that anymore. That's because we've cached the file to local disk and it can be served directly from there by the web server without going through rails. Mongrel does this by default on your local development setup, but your production environment might require some configuration to make sure that happens. The guys at Rails envy have a great article that has the details on how to configure our web and application servers to do that. The article provides more detail on page caching as well, including how to clear the cache when images change, so you should definitely check that out.

Posted in Technology | Tags Rails, Ruby, Caching

Comments Comments Feed

1. I do feel it's worth pointing out the major downside of this approach: the entire image is loaded into a Ruby String anytime you are working with that model (by default). This can get to be a significant burden on a large traffic site with serving many images. I had a database teacher who always use to remind us, "File data belongs in a file system."

# Posted By James Edward Gray II on Thursday, May 15 2008 at 9:17 AM

2. @James

That is true, this example was meant to mostly show how to download the image and use caching. For a real app, I would use attachment_fu and store the file data in a separate table, and attachment_fu supports that with the db_file option. The only time you even load that record would be in this controller, when the file gets cached.

One advantage of keeping the data in the DB is that there are no extra operations required to keep the file on the file system and record in the DB in sync. Also, you can just backup your database and you get the file data right along with it. Also if you have more than one app server, the file data is stored in a central location. But on a large app, storing a lot of file data in the DB could make the DB harder to manage, so storing the file data on a shared file system would make more sense. But for small to medium sites, as long as you keep the file data in a separate table from the record that has the data about the file, I prefer to keep everything the DB, YMMV.

# Posted By Paul Barry on Thursday, May 15 2008 at 10:25 AM

3. Storing files in a database is not really a problem, since most database servers have great support for it.

I use this approach to store small thumbnails in my database. By using a has_many relation I can easily access my data without loading all the Photo data. I only load it when I need it. In combination with the caching feature, this is a very acceptable solution.

# Posted By Ariejan de Vroom on Thursday, September 11 2008 at 8:38 AM

4. great example! right what I was looking for... now I'm trying to resize the image before storing it into the db... any tip or tutorial you'd suggest? Google is not helping at all so far :P

thanks for the example again!

# Posted By david on Monday, January 26 2009 at 5:41 PM

5. brian atwood maniac pumps the perfect wear-with-everything color. These wardrobe staples have 5" stiletto heels and hidden 1 1/2" seamless platforms. These Brian Atwood 'Loca' studded pumps are so ravishing, that I'd totally be willing to pop an aspirin before wearing them. And I really lovebrian atwood mesh sandals and Brian Atwood Asymmetric Patent Pumps.brian atwood nude patent leather katie lee pumps. Bold shoes like these sculptural purple suede Brian Atwood 'Lola' pumps make an outfit. purple suede Brian Atwood 'Lola' pumpswith a heel that measures approximately 140mm / 5.5 inches with a 30mm / 1 inch concealed platform. Brian Atwood pumps have a closed toe, cutout detail at arch with elasticated straps and a leather sole.
Herve Leger Dress shop specialises in superior Herve Leger Dress, provides hundreds of discount and fashion Herve Leger Dress, sexy Herve Leger Dress, Herve Leger Skirt, disount Herve Leger Dress-a professional Herve Leger Shop.

# Posted By Brian Atwood maniac pumps on Saturday, August 28 2010 at 6:16 AM

6. Wonderful brian atwood shoes for your style.BRIAN ATWOOD High-heeled sandals Purple is in stock in our store only one size in 36.5 EU. Elegant purple color, you will like it.
And these Pink Brian Atwood Maniac Patent Platform Pumps not only romantic and gorgeous too! It's patent leather leave us sunshine warmness and sexy!
When I original saw these brian atwood loca studded pumps in a metallic version, a while ago, I likeable them OK, but now I am going unhinged for the lavender version!
I really love brian atwood nico patent pump.
And this year, brian atwood maniac pumps are so hot among stars, I saw many times that Victoria-Beckham wearing them on the show time.
If you don’t know about brian atwood…You should. When everyone else is obsessing over the latest pair of Loubs or YS’L’s it’s very easy to overlook awesome shoe lines and designers who push the envelope. brian atwood is one of those designers.I’m a fan of his lines because Atwood really sets out to make his shoes a conversation piece. The use of alternative textures and fabrics makes brian atwood shoes unique. When wearing his shoes you are guaranteed a compliment from someone and a definate shoe in for best footwear. So ladies (and gents) get into these! And I know my card carrying “Shoe Wh*res” are going to love these!
Buy brian atwood shoes at http://www.brianatwoodcom.com. Buy brian atwood pumps at http://www.brianatwoodcom.com/brian-atwood-brian-atwood-pumps-c-65_67.html.
When I original saw these brian atwood loca studded pumps in a metallic version, a while ago, I likeable them OK, but now I am going unhinged for the lavender version!
When it comes to intricate detailing and superb craftsmanship, you know a pair of brian atwood lexia is worth the investment.
Back by popular demand... brian atwood maniac tan, the perfect wear-with-everything color. These wardrobe staples have 5" stiletto heels and hidden 1 1/2" seamless platforms. In a beautiful, very neutral nude tan.
brian atwood whip snake shoe with Exotic whipsnake hidden platform and back metal inset.
Take a walk on the wild side with Atwood Jagger printed knee-high boots. Style them knee high to add sass to an LBD or wear them with the fold-over flap turned up to work this season's hot over-the-knee trend.
brian atwood cage peep Price: $228. 140mm Covered heel. Rounded peep toe. 40mm covered platform. Interwoven cut outs around front. Ankle strap with adjustable metal buckle. Leather insole and lining. Leather sole. Made in Italy.
When it comes to intricate detailing and superb craftsmanship, you know a pair of brian atwood crystal court shoe is worth the investment.
Brian Atwood Platform Chain Pumps with A silver chain scales the lace-up back of this vamped-up pumps.
brian atwood snakeskin platforms is the classic and the elastic heel detail was used again from last Fall.
brian atwood patent leather and mesh Futuristic patent leather style with mesh details and contrast stitching.
Heel measures approximately 95mm/ 3.5 inches. Let your feet do the talking in brian atwood dorota shoes. Wear this chic style with off-duty denim or to liven up office looks.

# Posted By Brian Atwood loca studded pumps on Saturday, August 28 2010 at 6:17 AM

7. A grand wedding on the beach may be the common dream of most single girls. The bright sunshine, the blue sky and the open sea can satisfy all the demands of the romantic girls. Of course, everything will be perfect with a beach wedding dresses.
Every woman deserve the most beautiful wedding dresses at her special day!The most beautiful smile in the word is belong to the brides when she find her wedding dresses!Love is the time when you slows down in front of the shops selling wedding dresses.
Make the day of your engagement a special one with a A-line or princess wedding dresses!Step like a goddess in tea- length ball gowns,formal ball gowns,victorian ball gowns,debutante ball gowns,prom ball gowns, contemporary ball gownsand vintage ball gowns available in chiffon, organza, silk and satin only at weddingdressesnow.com.
Congratulations! Your little daughter is getting married! But being the mother of the bride (or MOB) is not an easy role. Once upon a time mothers of the bride did most of the wedding planning, and thus got to have their own dreams realized. First of all, choose one from the perfect mother of the bride dresses for yourself here and to be the most elegant mother of bride!
Flower girl dresses must be the perfect accessory for the bride's dress. The flower girls look like the bells ring in the wedding announcements as they toll down the aisle one by one or hand in hand. If you are having flower girls at your wedding, take a look at these beautiful selection of Flower girl dresses from http://www.weddingdressesin.com.

# Posted By A line wedding dresses on Saturday, August 28 2010 at 6:17 AM

8. Find ugg and Australian sheepskin boots, learn the history behind the Ugg boot, and when and what to wear with Cheap ugg boots, as well as cleaning and caring forAuthentic Ugg boots,Cheap ugg cardy boots,20%-40% high discount

# Posted By p on Wednesday, September 1 2010 at 2:12 PM

9.

Cheap nfl jerseys are your best choice,a newly released innovative product that will discounted nfl jerseys help you in your sport, or a one of a kind toddler nfl jerseys collectible that you will keep in your family for generations.Quality first,infant nfl jerseys Customer forever, GUARANTEE SHIPPING is our persistent tenet.

# Posted By fewrewree on Wednesday, September 1 2010 at 7:26 PM

10.

Cheap nfl jerseys are your best choice,a newly released innovative product that will discounted nfl jerseys help you in your sport, or a one of a kind toddler nfl jerseys collectible that you will keep in your family for generations.Quality first,infant nfl jerseys Customer forever, GUARANTEE SHIPPING is our persistent tenet.

# Posted By fewrewree on Wednesday, September 1 2010 at 7:26 PM

11. linda
Gucci Designer handbags are not rightful simple leather lacoste Gucci Outlet men embroidered carrier items imperative for the jurisdiction of girlie items drink in toiletries, make-up and authorize UGG Boots. No girlfriend! An authentic designer MBT Shoes speaks volumes about you and implies that you are a witch of style, seasoning and UGG Boot. However, you power serve as assurance that having an authentic nike dunk is facade your carry through. You Cheap Gucci substitute wonderment if you passion to crack into MBT Discount savvy a blasting move shift you have your pocket dunk shoes and house till you dispatch to that unknown pace when you be credulous saved enough to buy your confess authentic designer bag.

# Posted By nike dunk on Thursday, September 2 2010 at 2:13 AM

12. Coach
Coach handbags
Coach bags
replica Coach

# Posted By ss on Thursday, September 2 2010 at 7:46 AM

Add a Comment

(If you leave this blank, your IP address will be displayed instead)

(Optional, will not be displayed on the site)