Quick Tip: Using the HTML5 “download” Attribute

Creating a download link in HTML is straightforward; add an anchor tag and point to the file within the href attribute. Some file types, however, (such as images, .pdf, .txt, and .doc for example) won’t be downloaded. They, instead, will be opened in the browser.

If you have server-side access to your website there are some workarounds you can use, such as configuring the .htaccess, to download these files directly. If your site is hosted with a free service like WordPress.com, Blogspot, or perhaps Github pages which don’t allow you to do so, consider using the download attribute.

Using the “Download” Attribute

The download attribute is part of the HTML5 spec and expresses a link as download link rather than a navigational link.

The download attribute also allows you to rename the file name upon downloading. When the file resides on the server, especially if it’s been automatically generated, it may be named systematically with numbers and dashes, for example acme-doc-2.0.1.txt. It would be better for users to receive the file with a more sensible name when downloaded, perhaps like: Acme Documentation (ver. 2.0.1).txt (not forgetting the file extension).

Here’s how that would look in practice:

Give it a try on the demo page, and you should find the file downloaded with the name specified in the download attribute.

A Couple of Notes:

  • Firefox only allows users to download files of the same origin due to a security concern. The file must come from your own server or domain name, otherwise it will be opened in the browser.
  • While downloading cross-origin files is allowed in Chrome and the latest Opera (with Chromium/Blink), they will both ignore the attribute value. In other words, the file name will remain unchanged.

Providing Fallback

At the time of writing, the download attribute is not yet implemented in Safari and (as you might expect) Internet Explorer. Saying that, according to modern IE status, it is currently at the top of the development list and receiving a great deal of votes. 

In the meantime, we can add a decent fallback, such as providing extra instructions below the download link for non-supporting browsers. To do so, we will need to download Modernizr with the download feature test included.

Configure Modernizr build.

Then we can add the following script.

The script will test whether the browser supports the download attribute; if not it will append a new <div> with the class for styling purposes as well as the instruction text, and insert it immediately below any link which has been furnished with the download attribute.

The text instruction appears in Safari.

Wrapping Up

The download attribute makes handling download links very convenient for anyone who has no access to server-side configuration. I’m looking forward to Internet Explorer and Safari implementing the download attribute soon!