Browser/html Force download of image from src="data:image/jpeg;base64..."
To download a base64 image from your browser, utilize an <a>
tag with the download
attribute. Set the href
to the image data and download
to your desired file name. Here is an example:
Give it a click, and voila! Instantaneous download of your image with the specified filename.
Handling various browsers and their quirks
Programming always involves being one step ahead and handling cases that slip out of the norm. Browsers have their own personalities, and to gel with all, we need to consider several edge cases and plan our strategy.
Blob: A friend for older browsers
For those old-timers who still swear by older browsers or those handling larger files, the way to extract image data is to convert the data URI to a respectable blob. This ensures smooth sailing and compatibility. Here's how you do it.
You now have a safer and more reliable approach to download the image across diverse environments.
Javascript strikes: Enhance your user experience
To add that extra oomph to your UX, Javascript comes into play. Here's how to let your download take off without needing the user to click a link:
Alternatively, to change the current page location for direct downloads, go with:
Both methods give your user a sense of familiarity while improving navigation.
Upgrading download attribute for guided downloads
When you want to download dynamically generated content or if your user loves surprises (no user interaction), the simple anchor tag won't do. Here comes the need to enhance the download attribute. Brace yourself for some Javascript magic and dynamic handling!
JavaScript: Alter the image before download
If the image data isn't readily available as a data URI, we can draw the image onto a canvas element, and then extract the data URI.
Libraries for the vanishing act: FileSaver.js
FileSaver.js is a life-saver when you want to write less but get more done. This cross-browser compatible library effortlessly deals with browser-specific quirks and saves the day (and your file!).
Just a snippet of code, and your file is saved!
References
Was this article helpful?