I have converted an image into dataurl
using FileReader
and it gives me output like:
data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD//gA7Q1JFQVRPUjogZ2QtanBl…Vp1m8u4+SV/s0TpD8+91R/3Xlf8sXZv9Y9OGLk5eyVnCNu19Ntdu2jYOnaHtG7ffb7t/uP/9k=
Which is a very long string..
Now I again want to convert it to file object so that I can post this image.
How can I again convert this image into file object
URL.createObjectURL() The URL.createObjectURL() static method creates a string containing a URL representing the object given in the parameter. The URL lifetime is tied to the document in the window on which it was created. The new object URL represents the specified File object or Blob object.
The readAsDataURL method is used to read the contents of the specified Blob or File . When the read operation is finished, the readyState becomes DONE , and the loadend is triggered. At that time, the result attribute contains the data as a data: URL representing the file's data as a base64 encoded string.
It works by creating a FileReader object and creating a listener for load events such that when then file is read, the result is obtained and passed to the callback function provided to read() . The content is handled as raw text data.
Converting dataurl
to File Object
var byteString = atob(dataURI.split(',')[1]);
var ab = new ArrayBuffer(byteString.length);
var ia = new Uint8Array(ab);
for (var i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
var blob = new Blob([ia], { type: 'image/jpeg' });
var file = new File([blob], "image.jpg");
based on @William-t answer / more discussion on stackoverflow.com/questions/4998908/
MDN blob file
A Blob object represents a file-like object of immutable, raw data. Blobs represent data that isn't necessarily in a JavaScript-native format. The File interface is based on Blob, inheriting blob functionality and expanding it to support files on the user's system.
MDN FormData
var form = new FormData(),
request = new XMLHttpRequest();
form.append("image", blob, "myimage.jpg");
request.open("POST", "/upload", true);
request.send(form);
You can use fetch to convert an url to a File object.
//load src and convert to a File instance object
//work for any type of src, not only image src.
//return a promise that resolves with a File instance
function srcToFile(src, fileName, mimeType){
return (fetch(src)
.then(function(res){return res.arrayBuffer();})
.then(function(buf){return new File([buf], fileName, {type:mimeType});})
);
}
//usage example: (works in Chrome and Firefox)
srcToFile(
'data:image/gif;base64,R0lGODlhDgANAKIAAAAAAP///9HV2U5RU////wAAAAAAAA'
+ 'AAACH5BAEAAAQALAAAAAAOAA0AAAMXSLrc/hCO0Wa1atJLtdTbF0ZjZJ5oyiQAOw==',
'arrow.gif',
'image/gif'
)
.then(function(file){
console.log(file);
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With