How to download a base64 image in JavaScript
When you are dealing with the content of an image file. You may receive base64 image content in string format. So today we will show you how to download base64 image in JavaScript.
Checkout more articles on JavaScript
Let’s assume that you have base64 image string base64-image-string
that we have to download in image form using JavaScript.
Download base64 image
1 2 3 4 5 6 7 8 9 | function downloadBase64File(base64Data, contentType, fileName) { const linkSource = `data:${contentType};base64,${base64Data}`; const downloadLink = document.createElement("a"); downloadLink.href = linkSource; downloadLink.download = fileName; downloadLink.click(); } downloadBase64File('base64-image-string', 'image/png', 'test.png'); |
Here, we have created the a
tag and set the href
& download
attributes. Then immediately call the click event to download the file.
You can use the above function to download any file such as jpeg
, text
, etc.
I hope you find this article helpful.
Thank you for reading. Happy Coding..!! 🙂