I want to download an image in JS which is base64 encoded. For this, I have first decoded the image and tried to download it. The file is downloading but the content in the downloaded files are nothing.
The encoded image is like:
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==
I used the following code to decode and download the image:
var imgdata = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==';
var imggetbase64decode = imgData.replace(/^data:image\/(png|jpg);base64,/, ""); // imgData is the encoded base64 string.
var data = imggetbase64decode, fileName = "my-download.png";
var a = document.createElement("a");
document.body.appendChild(a);
a.style = "display: none";
var json = data,
blob = new Blob([json], {type: "octet/stream"}),
url = window.URL.createObjectURL(blob);
a.href = url;
a.download = fileName;
a.click();
window.URL.revokeObjectURL(url);
I got the error during opening the downloaded file is:
Could not load image 'my-download.png'.