How to force files to open in the browser instead of downloading?

Alfred Francis
1 min readJun 23, 2021

Often we need to force some file links to directly open in the browser such as Receipts, PDFs etc. To draw an image in-browser, you have to send few HTTP headers.

First, it is the type of data.

Content-Type: image/png or image/jpeg or application/pdf

Next, is data length. Without this header, the browser will not know where the data ended.

Content-Length: 157304

To indicate to the browser that the file should be viewed in the browser, the HTTP response should also include the following header:

Content-Disposition: inline; filename="filename.png"

The quotes around the filename are required if the filename contains special characters such as filename[1].png which may otherwise break the browser's ability to handle the response.

How you set the HTTP response headers will depend on your HTTP server (or if you are generating the PDF response from server-side code: your server-side programming language).

Below is a Python- Flask code snippet to do the same

@app.route("document/<ObjectId:document_id>")
def get_document_link(document_id):
png_file = get_page(document_id)
return Response(
png_file,
mimetype="image/png",
direct_passthrough=True,
headers={"Content-Disposition": "inline;filename=img.png"}
)

To have the file downloaded rather than viewed:

Content-Disposition: attachment; filename="filename.png"

--

--

Alfred Francis

Full Stack Dev. Python, Java, Go,Angular, React, AWS. Interested in Virtual Assistants and SaaS.