How to convert Base64 String to javascript file object like as from file input form?
Way 1: only works for dataURL, not for other types of url.
function dataURLtoFile(dataurl, filename) { var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1], bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n); while(n--){ u8arr[n] = bstr.charCodeAt(n); } return new File([u8arr], filename, {type:mime}); } //Usage example: var file = dataURLtoFile('data:text/plain;base64,aGVsbG8gd29ybGQ=','hello.txt'); console.log(file);
Way 2: works for any type of url, (http url, dataURL, blobURL, etc...)
//return a promise that resolves with a File instance function urltoFile(url, filename, mimeType){ return (fetch(url) .then(function(res){return res.arrayBuffer();}) .then(function(buf){return new File([buf], filename,{type:mimeType});}) ); } //Usage example: urltoFile('data:text/plain;base64,aGVsbG8gd29ybGQ=', 'hello.txt','text/plain') .then(function(file){ console.log(file);});
const url = 'data:image/png;base6....';fetch(url) .then(res => res.blob()) .then(blob => { const file = new File([blob], "File name",{ type: "image/png" }) })
Base64 String -> Blob -> File.
This is the latest async/await
pattern solution.
export async function dataUrlToFile(dataUrl: string, fileName: string): Promise<File> { const res: Response = await fetch(dataUrl); const blob: Blob = await res.blob(); return new File([blob], fileName, { type: 'image/png' });}