How To Download File Using Anchor Tag

By bhagwatchouhan
How To Download File Using Anchor Tag

HTML5 introduced the download attribute of the anchor tag to add downloadable behavior to it. We can use the anchor tag to download a file by specifying the name of the downloadable file. Most of the modern browsers support the download attribute.

The way to use it as shown below. We can either omit the name or provide a new name with or without extension. In case download attribute value is not specified, the browser will use the file name from the href value.

Replace the href and download attribute with the actual link and the file name to be saved.

// Download an Image
<a href="/images/image.jpg" download>Download</a>
<a href="/images/image.jpg" download="myimage">Download</a>
<a href="/images/image.jpg" download="myimage.jpg">Download</a>

// Download Zip
<a href="/docs/" download>Download</a>
<a href="/docs/" download="mycompressed">Download</a>
<a href="/docs/" download="">Download</a>

// Download PDF
<a href="/docs/document.pdf" download>Download</a>
<a href="/docs/document.pdf" download="mydocument">Download</a>
<a href="/docs/document.pdf" download="mydocument.pdf">Download</a>

In certain situations, the browser tries to open the file even after using the download attribute E.g. it opens the pdf in the browser itself. The exceptions are as listed below.

Content-Disposition Header - If the Content-Disposition header provides a different filename than the Content-Disposition will take precedence irrespective of the download attribute value.

PDF File - Browsers open the PDF file irrespective of using download attribute. This behavior can be changed by changing browser settings. We can force the same from the server in case the website is served by Apache or NGINX by adding the below-mentioned configuration.

# Add to htaccess of Apache
ForceType application/octet-stream
Header set Content-Disposition attachment
# NGINX Solution
location ~* (.*\.pdf) {
types { application/octet-stream .pdf; }
default_type application/octet-stream;

share on :

Profile picture for user bhagwatchouhan