DEV Community

Alexander Budchanov
Alexander Budchanov

Posted on • Originally published at jetrockets.pro

1 1

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">
Enter fullscreen mode Exit fullscreen mode

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";
}
Enter fullscreen mode Exit fullscreen mode

for Apache:

<IfModule mod_headers.c>
    <FilesMatch "\.(?i:pdf)$">
        ForceType application/octet-stream
        Header set Content-Disposition "attachment"
    </FilesMatch>
</IfModule>
Enter fullscreen mode Exit fullscreen mode

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more