Force Downloading of File instead of Opening in Browser


When you go through the link, some files will be opened in the browser. Such behavior is typical for some content types (e.g., images, pdf, etc.)

However, you can force file downloading instead of opening when an user clicks on the link though.

1st way (frontend):

HTML attribute download allows you to do this.


<a href="/public/report.pdf" download="stat_report">

If the value of the attribute is omitted, the original filename would be used.

However, be careful. This attribute isn’t supported in some old browsers without HTML5 support.

Renaming does not work if the given file stored on another host.

2nd way (backend):

You can set HTTP header Content-disposition.

for Nginx:


location ~* /public/(.+\.pdf)$ {

    add_header Content-disposition "attachment; filename=$1";

}

for Apache:


<IfModule mod_headers.c>

    <FilesMatch "\.(?i:pdf)$">

        ForceType application/octet-stream

        Header set Content-Disposition "attachment"

    </FilesMatch>

</IfModule>


Alexander
Budchanov

Backend Developer at JetRockets

Explore more of JetRockets