To offer a download image or file in your website you need to return a correct Django response. That response must contains the header Content-Disposition with the value of attachment
Step 1: Prepare the HttpResponse
First thing first is to open the file in the binary mode and include it in the http response. Also use appropriate MIME for the content_type.
with open(file_path, "rb") as fprb:
response = HttpResponse(fprb.read(), content_type="image/png")
Step 2: Attach the Content-Disposition header
This header is responsible for what the browser should do with the response. Whether display it in the browser itself ( default value inline
) or attachment
where consider the whole attachment as the download.
response["Content-Disposition"] = "attachment; filename=preview-card.png"
Here the filename is optional but if you provide the browser will use that name to save your file.
Step: 3: Return the response
Finally you can return the response and when user clicks the download button in Django it will return the response as the download file instead of showing it in the browse.
with open(file_path, "rb") as fprb:
response = HttpResponse(fprb.read(), content_type="image/png")
response["Content-Disposition"] = "attachment; filename=preview-card.png"
return response
Conclusion
If you don’t want to modify the response you can also return a FileResponse which have the option as above.
return FileResponse(fprb.read(), as_attachment=True, filename="preview-card.png")