How to Force File Downloads with Anchor Tags in HTML
By default, web browsers open anchor links within the currently open tab and attempt to display the contents directly in the browser. These links include other HTML pages, PDF files, MP3 files, or any other file type able to be viewed within a browser window.
Download Files with Anchor Links
You can circumvent this behavior by adding the optional
download attribute to your anchor link, instructing the browser to force-download the file specified in your
href attribute instead of viewing it.
For example, let's say you run an e-commerce site and need a way for your users to download a receipt in PDF format once they've successfully placed an order. While a typical anchor link would look something like this:
<a href="/path/to/receipt.pdf">Download Receipt</a>
It would only navigate the user to the PDF file within the browser. To instruct the browser to instead force-download the file, you can add the
download attribute to the anchor link:
<a href="/path/to/receipt.pdf" download>Download Receipt</a>
Specifying A New File Name
With this scenario, order confirmation files usually aren't stored on servers with the filename receipt.pdf and may include more information like an order ID or order date.
You can specify a more readable and user-friendly file name with the same attribute:
<a href="/path/to/receipt-2187-0123456789.pdf download="receipt.pdf">Download Receipt</a>
Instead of downloading the PDF file with the long file name, it will now download to your device as the more readable receipt.pdf.
download attribute works in most modern browsers, including Google Chrome, Firefox, and Microsoft Edge, with only a few caveats:
- In Google Chrome, you can't download cross-origin files (files hosted on other domain names), so make sure your anchor links point to a valid URL within the same domain.
- This attribute doesn't work in Internet Explorer, but since Microsoft no longer provides support for IE, you should be in the clear.
download attribute for HTML anchor links is a life-saver and simple solution.
There are no comments yet. Start the conversation!