A web developer's blog. PHP, MySQL, CakePHP, Zend Framework, Wordpress, Code Igniter, Django, Python, CSS, Javascript, jQuery, Knockout.js, and other web development topics.

Django: Reading an image outside the public accessible directory and displaying the image through the browser

In some cases you would want to have “private” images for your logged-in users, you will not be able to store the images in the public accessible directory.

For example, if you have “my_private_photo.png” stored in your normal “images” directory, any user (logged in or not) will be able to do this in the URL bar:

http://www.yourwebsite.com/images/my_private_photo.png

When an anonymous user does that, he would be able view the private image.

To do this, you must store your “private images” outside the public accessible directory. In this example, we will put the private images in:

/home/wenbert/private_storage

Before I proceed, please take note that this example will use X-Sendfile. Please refer to my post on how to install and configure X-Sendfile in your Apache webserver.

Now for the view.py, it would look something like this:

def display_image(request, image_id):
    path = "/home/wenbert/private_storage"
    file = image_id
    filepath = os.path.join(path,file)
 
    #Here, you put your code to check whether the user has access to this photo or not
 
    response = HttpResponse(mimetype=mimetypes.guess_type(filepath)) 
    response['Content-Disposition']='filename="%s"'
                                    %smart_str(file)
    response["X-Sendfile"] = filepath
    response['Content-length'] = os.stat(filepath).st_size
 
    return response

In your urls.py, you would want to add something like this:

(r'^display_image/(?P<image_id>d+)/$', display_image)

With this, you should be able to output images through your templates using the normal IMG tag. For example:

<img src="/display_image/private_photo.png" />

Note that I have hard-coded “private_photo.png”. This is assuming I already know the “image id” you want to display.

Comments/questions/suggestions, do not hesitate to post them below.

I hope that was helpful.

This entry was posted in General and tagged , , . Bookmark the permalink.

One Response to Django: Reading an image outside the public accessible directory and displaying the image through the browser

  1. iijmae says:

    Hello there, I am new in zend. Let say i already got the image path as $file,
    how to show my image? I have tried imagepng($file); but it says that the image cannot be opened cause it contains error. Can you help me?

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>