Sometimes, we want to convert Base64 string to JavaScript file object like as from file input form.
In this article, we’ll look at how to convert Base64 string to JavaScript file object like as from file input form.
How to convert Base64 string to JavaScript file object like as from file input form?
To convert Base64 string to JavaScript file object like as from file input form, we can use fetch.
For instance, we write
const urlToFile = async (url, filename, mimeType) => {
const res = await fetch(url);
const buf = await res.arrayBuffer();
return new File([buf], filename, { type: mimeType });
};
(async () => {
const file = await urltoFile(
"data:text/plain;base64,aGVsbG8gd29ybGQ=",
"hello.txt",
"text/plain"
);
console.log(file);
})();
to define the urlToFile function that calls fetch with the url to return a promise with the res response object.
Then we call res.arrayBuffer to get the response as an array buffer.
Next, we create a File object with the buf buffer with the given mimeType and return that as the resolve value of the promise returned by urlToFile.
Then we call urlToFile with the base64 URL, file name, and the MIME type of the file to return a promise with the file.
Conclusion
To convert Base64 string to JavaScript file object like as from file input form, we can use fetch.