Using the HTML download attribute, you can trigger the browser to download the referred asset instead of opening it.
With HTML5 we got some vast, and cool stuff like the Web Storage, History, Web Workers API-s but the update was not just about these more prominent features. There is a lot more little piece like the download attribute, which is a more solid feature but still a handy one.
The Purpose of the HTML Download Attribute
In modern browsers, it is common to open an asset. The modern browsers try to open every external resource like the PDF, image files. But what is the situation if you want to avoid this behavior? You apply the download attribute to the <a> tags with the specific URLs.
To achieve this behavior – make an asset downloadable – was always possible with PHP using the proper headers, but it is a practice that it is available only with HTML.
Using the Download Attribute
The using is plain simple. The attribute only works on <a> tags.
<a href="/images/profile-photo.jpg" download>
We can also give a value to the attribute, which will be the downloaded file’s name. This feature could be useful if a downloadable content file name is generated dynamically and you want to hide it because it is irrelevant for the user.
<a href="/images/pdf-modified-2019-06-27.jpg" download="proposal">
// You can also set new names with spaces. <a href="/images/pdf-modified-2019-06-27.jpg" download="Proposal for Pine">
Download Restrictions
The browsers will only serve files which are located on the same-origin URL as the hyperlink. It is a generic behavior supported by the vendors, which protect the web from malicious files and codes.
Nice to Known Features
- The HTML download attribute can be a blob or data URI so we can trigger download on dynamically created elements through JavaScript.
- You can also use the download attribute on <area> tags in image-maps.
- There aren’t any file extension restrict.
- We don’t need to set the file extension; the browser will handle it.
- There are naming restriction which comes from the operating system. If you give a forbidden character, which isn’t supported on your OS, you get the original filename.
Browser Support
The support could be better. In the next Safari, we get this feature. IE does not support it, but with the Edge, it isn’t a big problem today.
Conclusion: HTML Download Attribute
The usefulness of this rarely used attribute is clean like in the case of the <time> element. You can decide from your HTML code when you like to make your external files downloadable instead of open.