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

后端 未结 5 1165
忘了有多久
忘了有多久 2020-11-28 06:43

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:

<
相关标签:
5条回答
  • 2020-11-28 07:10

    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' });
    }
    
    0 讨论(0)
  • 2020-11-28 07:14

    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);});

    0 讨论(0)
  • 2020-11-28 07:17
    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.

    0 讨论(0)
  • 2020-11-28 07:17

    I had a very similar requirement (importing a base64 encoded image from an external xml import file. After using xml2json-light library to convert to a json object, I was able to leverage insight from cuixiping's answer above to convert the incoming b64 encoded image to a file object.

    const imgName = incomingImage['FileName'];
    const imgExt = imgName.split('.').pop();
    let mimeType = 'image/png';
    if (imgExt.toLowerCase() !== 'png') {
        mimeType = 'image/jpeg';
    }
    const imgB64 = incomingImage['_@ttribute'];
    const bstr = atob(imgB64);
    let n = bstr.length;
    const u8arr = new Uint8Array(n);
    while (n--) {
      u8arr[n] = bstr.charCodeAt(n);
    }
    const file = new File([u8arr], imgName, {type: mimeType});
    

    My incoming json object had two properties after conversion by xml2json-light: FileName and _@ttribute (which was b64 image data contained in the body of the incoming element.) I needed to generate the mime-type based on the incoming FileName extension. Once I had all the pieces extracted/referenced from the json object, it was a simple task (using cuixiping's supplied code reference) to generate the new File object which was completely compatible with my existing classes that expected a file object generated from the browser element.

    Hope this helps connects the dots for others.

    0 讨论(0)
  • 2020-11-28 07:18

    Heads up,

    JAVASCRIPT

    <script>
       function readMtlAtClient(){
    
           mtlFileContent = '';
    
           var mtlFile = document.getElementById('mtlFileInput').files[0];
           var readerMTL = new FileReader();
    
           // Closure to capture the file information.
           readerMTL.onload = (function(reader) {
               return function() {
                   mtlFileContent = reader.result;
                   mtlFileContent = mtlFileContent.replace('data:;base64,', '');
                   mtlFileContent = window.atob(mtlFileContent);
    
               };
           })(readerMTL);
    
           readerMTL.readAsDataURL(mtlFile);
       }
    </script>
    

    HTML

        <input class="FullWidth" type="file" name="mtlFileInput" value="" id="mtlFileInput" 
    onchange="readMtlAtClient()" accept=".mtl"/>
    

    Then mtlFileContent has your text as a decoded string !

    0 讨论(0)
提交回复
热议问题