Create a Downloadable Link using HTML5 Download Attribute
The default of your anchor tag is a navigational link, it will go to the link you specified in your
However, when you add the
download attribute, it will turn that into a download link. Prompting your file to be downloaded. The downloaded file will have the same name as the original filename. However, you can also set a custom filename by pass a value to the download attribute 🤩
<a href="/samanthaming.png" download> Download with original filename -> samanthaming.png </a> <a href="/samanthaming.png" download="logo"> Download with custom filename -> logo.png </a>
download attribute only works for same-originl URLs. So if the
href is not the same origin as the site, it won't work. In other words, you can only download files that belongs to that website. This attribute follows the same rules outline in the same-origin policy.
What is the same-origin policy?
This policy is a security mechanism that helps to isolate potentially malicious documents and reduce possible attack vectors. So what does that mean for our
download attribute? Well, it means that users can only download files that are from the origin site. Let's take a look at an example:
||This will work|
||This won't work|
You can learn more about this policy on the MDN Web Doc
This feature is not supported by all browsers (cough cough IE). So if there is a specific browser you're targeting, make sure you check compatibility before using this attribute.
@vikneshwaran_jk: I have used this download attribute in my personal portfolio website to make my resume as downloadable(pdf). Simply powerful👌
chriskelly7777: A very handy tip. A little gotcha that caught me off guard initially is that this only works on same origin requests, not cross origin, where it is ignored: Stack Overflow - just to save anyone else pulling out their own hair like I did