How to download a base64 image in JavaScript
๐
May 8, 2022
๐JavaScript
When you are dealing with the content of an image file. You may receive base64" title="Base64">base64 image content in string" title="string">string format. So today we will show you how to download base64 image in JavaScript.
Checkout more articles on JavaScript
- How to clear an HTML file input using JavaScript
- How to remove HTML tags from a string using JavaScript
- How to split a string in JavaScript
- screen-size-in-javascript" title="How to get the screen size in JavaScript">How to get the screen size in JavaScript
- url-in-a-new-tab-using-javascript" title="How to open an URL in a new tab using JavaScript">How to open an URL in a new tab using 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
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..!! ๐