Force browser to download image files on click
Want to download an image on click? The download
attribute is your best friend. Apply it to your anchor tag enclosing the image. href
states your image's URL and download
is your file's new name. For example:
Voila! Clicking the image prompts a download with the specified filename.
Dealing with compatibility and restrictions
Let's be brutally honest, not all browsers deal well with the download
attribute. Some just wouldn't listen. Want to provide feedback or alternate instructions? Try using some feature detection action:
Navigating CORS and those pesky cross-origin images
Having trouble with cross-origin images? Stuck because of some CORS policy? We've got a workaround. Download the image by setting the crossOrigin
attribute to anonymous
on an Image
object, drawing to a canvas, and then sparking the download:
Programmatically triggering a download with JavaScript
What if you want to dynamically trigger downloads using JavaScript? Well, here's the good news, you can create an anchor element:
Getting remote images and the fetch API
Want to grab images using the Fetch API? You can! Simply ensure to handle the response as a blob and use URL.createObjectURL()
:
Some extra toppings
When using the download
attribute, it's quite handy to extract the file name from the URL or obtain the image's MIME type. This ensures that your file format is correct and consistent. After all, nobody wants to download a jpg file as .xlsx!
Handling Dynamic changes and consistency
For dynamically generated content or user actions, you might need to create a temporary element for the download initiation:
Keeping up with changing Browser Standards
Attaining consistency across browsers could be a Herculean task, thanks to recent Chrome deprecations and other browser updates. Staying informed about these changes ensures your download functionality remains in shipshape!
Was this article helpful?