Let\'s say that I have an img tag with a base64 src like :
How can I create a
The File Object inherits the Blob object, so it is very close to being the same.
The code below shows a successfully generated File "Blob" object can be used to generate a object url which downloads the image.
( Note: on stack overflow the blob url has a null host which causes it to not to automatically download as a file, but you can still use right click save as. See URL.createObjectURL returns a blob with null prepended. Eg : Blob:null/12415-63 )
// https://bl.ocks.org/nolanlawson/0eac306e4dac2114c752
let dataUrl = document.getElementById("img1").src.split(',')
let base64 = dataUrl[1];
let mime = dataUrl[0].match(/:(.*?);/)[1];
let bin = atob(base64);
let length = bin.length;
// From http://stackoverflow.com/questions/14967647/ (continues on next line)
// encode-decode-image-with-base64-breaks-image (2013-04-21)
let buf = new ArrayBuffer(length);
let arr = new Uint8Array(buf);
bin
.split('')
.forEach((e,i)=>arr[i]=e.charCodeAt(0));
let f = new File([buf],'filename',{type:mime}); // note: [buf]
let blobUrl = URL.createObjectURL(f);
let link = document.createElement("a");
link.href = blobUrl;
link.download = "filename";
link.innerHTML = "Download file.";
document.getElementById("url1").appendChild(link);