Clue Mediator

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

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..!! ๐Ÿ™‚