Lorenzo Ang
Lorenzo Ang

Reputation: 1318

How to serve an image variable in a response?

When serving a file, we normally include it in the Response as such:

response['Content-Disposition'] = f'attatchment; filename="<file-path>"'

My issue however is I need to serve an image file from a variable. The image is stored on a different server which is downloaded, stored as a variable, and then needs to be attached to my Response object. Is this possible? Something like the following:

import PIL, io
from django.http import HttpResponse
img = PIL.Image.open(io.BytesIO(photo_bytes))
response = HttpResponse(content-type='image/png')
response['Content-Disposition'] = f'attatchment; filebytes="{photobytes}"'

Upvotes: 0

Views: 179

Answers (1)

Lorenzo Ang
Lorenzo Ang

Reputation: 1318

Figured it out! Apparently you can just write bytes to the response directly like so

response = HttpResponse(photo_bytes, content_type=f'image/png')

Upvotes: 1

Related Questions