I need to convert a dataURL to a File object in Javascript in order to send it over using AJAX. Is it possible? If yes, please tell me how.
I need to convert a dataURL to a File object in Javascript in order to send it over using AJAX. Is it possible? If yes, please tell me how.
To create a blob from a dataURL:
const blob = await (await fetch(dataURL)).blob();
To create a file from a blob:
const file = new File([blob], 'fileName.jpg', {type:"image/jpeg", lastModified:new Date()});
If you really want to convert the dataURL into File object.
You need to convert the dataURL into Blob then convert the Blob into File.
The function is from answer by Matthew. (https://stackoverflow.com/a/7261048/13647044)
function dataURItoBlob(dataURI) {
// convert base64 to raw binary data held in a string
// doesn't handle URLEncoded DataURIs - see SO answer #6850276 for code that does this
var byteString = atob(dataURI.split(',')[1]);
// separate out the mime component
var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];
// write the bytes of the string to an ArrayBuffer
var ab = new ArrayBuffer(byteString.length);
var ia = new Uint8Array(ab);
for (var i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
return new Blob([ab], { type: mimeString });
}
const blob = dataURItoBlob(url);
const resultFile = new File([blob], "file_name");
Other than that, you can have options on the File Object initialised. Reference to File() constructor.
const resultFile = new File([blob], "file_name",{type:file.type,lastModified:1597081051454});
The type should be [MIME][1] type(i.e. image/jpeg) and last modified value in my example is equivalent to Mon Aug 10 2020 19:37:31 GMT+0200 (Eastern European Standard Time)
In Latest browsers:
const dataURLtoBlob = (dataURL) => {
fetch(dataURL)
.then(res => res.blob())
.then(blob => console.log(blob))
.catch(err => console.log(err))
}