Let's say that I have an img tag with a base64 src like :
<img src="data:image/jpeg;base64,/9j/4AAQS..." id="id">
How can I create a File object (containing the data of the img tag) alike an object I would get after an user chose a file from a file input ? In order to upload it to a server later.
Like that one :
File { name: "a22919a70cf8458d654642e0bc2cd881.jpg", lastModified: 1521393615000, lastModifiedDate: Date 2018-03-18T17:20:15.000Z, webkitRelativePath: "", size: 40635, type: "image/jpeg" }
I'm not looking for getting a BLOB.
Let's say that I have an img tag with a base64 src like :
<img src="data:image/jpeg;base64,/9j/4AAQS..." id="id">
How can I create a File object (containing the data of the img tag) alike an object I would get after an user chose a file from a file input ? In order to upload it to a server later.
Like that one :
File { name: "a22919a70cf8458d654642e0bc2cd881.jpg", lastModified: 1521393615000, lastModifiedDate: Date 2018-03-18T17:20:15.000Z, webkitRelativePath: "", size: 40635, type: "image/jpeg" }
I'm not looking for getting a BLOB.
Share Improve this question edited Apr 19, 2018 at 15:57 asked Apr 19, 2018 at 15:38 user6225298user6225298 2- Possible duplicate of How to create a File object from binary data in JavaScript – Sunny Patel Commented Apr 19, 2018 at 15:40
- @SunnyPatel No, at the end the user create a BLOB and not a File object like you would get with a file input. – user6225298 Commented Apr 19, 2018 at 15:43
2 Answers
Reset to default 27You could always create a blob first and then convert that to a file.
But you hardly ever need a File instance. It will give you more headache trying to construct them then just using the blob. If you need to upload them to a server you need to use FormData
. And when you do you can append a blob and set the filename as a 3th argument
fd.append(field, blob, filename)
instead of appending a file
The file constructor arguments are the same as blob except between the parts
and the options
you pass in the filename.
File Object inherits the Blob object so you use them the same way in other apis as well
new File([parts], filename, options)
new Blob([parts], options)
Other thing is that different is file supports 1 more option... lastModified
IE/Edge can have Files but the constructor don't work. that's why you should use blobs...
const img = document.getElementById('id')
fetch(img.src)
.then(res => res.blob())
.then(blob => {
const file = new File([blob], 'dot.png', blob)
console.log(file)
})
<img id="id" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==">
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);
<img id="img1" src="data:image/png;base64, iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAB1klEQVR42n2TzytEURTHv3e8N1joRhZGzJsoCjsLhcw0jClKWbHwY2GnLGUlIfIP2IjyY2djZTHSMJNQSilFNkz24z0/Ms2MrnvfvMu8mcfZvPvuPfdzz/mecwgKLNYKb0cFEgXbRvwV2s2HuWazCbzKA5LvNecDXayBjv9NL7tEpSNgbYzQ5kZmAlSXgsGGXmS+MjhKxDHgC+quyaPKQtoPYMQPOh5U9H6tBxF+Icy/aolqAqLP5wjWd5r/Ip3YXVILrF4ZRYAxDhCOJ/yCwiMI+/xgjOEzmzIhAio04GeGayIXjQ0wGoAuQ5cmIjh8jNo0GF78QwNhpyvV1O9tdxSSR6PLl51FnIK3uQ4JJQME4sCxCIRxQbMwPNSjqaobsfskm9l4Ky6jvCzWEnDKU1ayQPe5BbN64vYJ2vwO7CIeLIi3ciYAoby0M4oNYBrXgdgAbC/MhGCRhyhCZwrcEz1Ib3KKO7f+2I4iFvoVmIxHigGiZHhPIb0bL1bQApFS9U/AC0ulSXrrhMotka/lQy0Ic08FDeIiAmDvA2HX01W05TopS2j2/H4T6FBVbj4YgV5+AecyLk+CtvmsQWK8WZZ+Hdf7QGu7fobMuZHyq1DoJLvUqQrfM966EU/qYGwAAAAASUVORK5CYII=">
<div id="url1"></div>