Serving images directly from database

Even though storing images in the database have its advantages/disadvantages, here is a small guide for those who want to store them in the database and serve them directly to the browser without having to generate a file first. This examples is based on the amazing web framework pylons.

In this example I want to serve small product images from my product controller.

In the product.py controller I have this method

def show_image(self, id, name):
    response.headers['Content-type'] = 'image/png'
    response.headers['Cache-Control'] = 'max-age=14400'
    response.headers['Pragma'] = ''
    product = Product.get_by(id=id)
    return product.image

Then in my mako template I have

<img src="url(controller='product', action='show_image', id='${c.product.id}', name='c.product.image_name')"/>

which will generate

<img src="/product/show_image/1/super-glue.png"/>

So whats happening is that when the page is loading the image tag, the show_image() function is called which fetches the image data from the database and returns the image data buffer to the template. The key for this to work is to set the appropriate headers so that the page know that the data returned is image/png through the Content-type. The name argument is just used to set a name for the image file on the connecting client so that the cached file will have a correct name.

11 Responses to “Serving images directly from database”

Leave a Reply