DEV Community

Filip Němeček
Filip Němeček

Posted on • Edited on • Originally published at nemecek.be

Django: How to send image file as part of response

In this short blog post I will show you how to send image from Django and display it on page with a single response.

The trick is to use base64 encoding which can turn your image into string which can then be passed as a part of response.

This can have few benefits, the image being part of response so no additional request to get the image is not needed. You can also prevent users from simply copying the link and sending it to someone. Of course they can always take a screenshot..

Or maybe you have project where you don’t want to deal with configuring STATIC_ROOT and all that serving files with Django requires.

The actual Django part is pretty short:



import base64

with open(image_path, "rb") as image_file:
    image_data = base64.b64encode(image_file.read()).decode('utf-8')

ctx["image"] = image_data

return render(request, 'index.html', ctx)


Enter fullscreen mode Exit fullscreen mode

Note: The "rb" option stands for "read binary".

Optionally you can add try except to catch FileNotFoundError and react accordingly.

Now we just need to display the content using <img> tag:

Base64 image data in <img> tag

The snippet above was showing my markdown error so hence the screenshot.

And that is it 🙂

Thanks for reading!

--
Need to focus on your iPhone? Get free WebBlock app for scheduled website blocking from the App Store!

Top comments (3)

Collapse
 
steelwolf180 profile image
Max Ong Zong Bao

Interesting I didn't know you can do that.

Collapse
 
nemecek_f profile image
Filip Němeček

Hi @highcenburg , do you know why the second snippet did not work in the DEV.TO editor? Thanks

Collapse
 
highcenburg profile image
Vicente G. Reyes

Hi, you can always open an issue if you feel like there's a bug on the platform
github.com/thepracticaldev/dev.to/...