I have a base64-encoded image from the server for which I want to force the download through JavaScript. Is is possible?
One way to convert an image file into a base64 string is to put it into a canvas. Then we can call the canvas's toDataURL method to convert it into a base64 string. We create the getBase64Image function that takes the url string for the URL of the image. Then we create an img eklement with the Image constructor.
Images encoded with Base64 can be embedded in HTML by using the <img> tag. This can help to increase the page load time for smaller images by saving the browser from making additional HTTP requests.
If you want to download it using JavaScript (without any back-end) use:
window.location.href = 'data:application/octet-stream;base64,' + img;
where img
is your base64 encoded image.
If you want to allow the user to specify a file name, use the download
attribute of the a
tag:
<a download="FILENAME.EXT" href="data:image/png;base64,asdasd...">Download</a>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With