Search code examples
javascripthtmlformsfilebase64

How to convert Base64 String to javascript file object like as from file input form?


I want to convert Base64String extracted from file(ex: "AAAAA....~") to a javascript file object.

The javascript file object what I mean is like this code:

HTML:

<input type="file" id="selectFile" > 

JS:

$('#selectFile').on('change', function(e) {
  var file = e.target.files[0];

  console.log(file)
}

'file' variable is a javascript file object. So I want to convert a base64 string to the javascript file object like that.

I just want to get file object by decoding base64 string (encoded by other app from a file) without html file input form.

Thank you.


Solution

  • 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[arr.length - 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,aGVsbG8=','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){
        if (url.startsWith('data:')) {
            var arr = url.split(','),
                mime = arr[0].match(/:(.*?);/)[1],
                bstr = atob(arr[arr.length - 1]), 
                n = bstr.length, 
                u8arr = new Uint8Array(n);
            while(n--){
                u8arr[n] = bstr.charCodeAt(n);
            }
            var file = new File([u8arr], filename, {type:mime || mimeType});
            return Promise.resolve(file);
        }
        return fetch(url)
            .then(res => res.arrayBuffer())
            .then(buf => new File([buf], filename,{type:mimeType}));
    }
    
    //Usage example:
    urltoFile('data:text/plain;base64,aGVsbG8=', 'hello.txt','text/plain')
    .then(function(file){ console.log(file);});