How to convert file to base64 in JavaScript?

前端 未结 7 1932
醉话见心
醉话见心 2020-11-22 06:34

Now I\'m getting File object by this line:

file = document.querySelector(\'#files > input[type=\"file\"]\').files[0]

I need to send thi

相关标签:
7条回答
  • 2020-11-22 06:35

    If you're after a promise-based solution, this is @Dmitri's code adapted for that:

    function getBase64(file) {
      return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = () => resolve(reader.result);
        reader.onerror = error => reject(error);
      });
    }
    
    var file = document.querySelector('#files > input[type="file"]').files[0];
    getBase64(file).then(
      data => console.log(data)
    );
    
    0 讨论(0)
  • 2020-11-22 06:36

    Modern ES6 way (async/await)

    const toBase64 = file => new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = () => resolve(reader.result);
        reader.onerror = error => reject(error);
    });
    
    async function Main() {
       const file = document.querySelector('#myfile').files[0];
       console.log(await toBase64(file));
    }
    
    Main();
    

    UPD:

    If you want to catch errors

    async function Main() {
       const file = document.querySelector('#myfile').files[0];
       const result = await toBase64(file).catch(e => Error(e));
       if(result instanceof Error) {
          console.log('Error: ', result.message);
          return;
       }
       //...
    }
    
    0 讨论(0)
  • 2020-11-22 06:47
    onInputChange(evt) {
        var tgt = evt.target || window.event.srcElement,
        files = tgt.files;
        if (FileReader && files && files.length) {
            var fr = new FileReader();
            fr.onload = function () {
                var base64 = fr.result;
                debugger;
            }
            fr.readAsDataURL(files[0]);
        }
    }
    
    0 讨论(0)
  • 2020-11-22 06:51

    Here are a couple functions I wrote to get a file in a json format which can be passed around easily:

        //takes an array of JavaScript File objects
        function getFiles(files) {
            return Promise.all(files.map(file => getFile(file)));
        }
    
        //take a single JavaScript File object
        function getFile(file) {
            var reader = new FileReader();
            return new Promise((resolve, reject) => {
                reader.onerror = () => { reader.abort(); reject(new Error("Error parsing file"));}
                reader.onload = function () {
    
                    //This will result in an array that will be recognized by C#.NET WebApi as a byte[]
                    let bytes = Array.from(new Uint8Array(this.result));
    
                    //if you want the base64encoded file you would use the below line:
                    let base64StringFile = btoa(bytes.map((item) => String.fromCharCode(item)).join(""));
    
                    //Resolve the promise with your custom file structure
                    resolve({ 
                        bytes: bytes,
                        base64StringFile: base64StringFile,
                        fileName: file.name, 
                        fileType: file.type
                    });
                }
                reader.readAsArrayBuffer(file);
            });
        }
    
        //using the functions with your file:
    
        file = document.querySelector('#files > input[type="file"]').files[0]
        getFile(file).then((customJsonFile) => {
             //customJsonFile is your newly constructed file.
             console.log(customJsonFile);
        });
    
        //if you are in an environment where async/await is supported
    
        files = document.querySelector('#files > input[type="file"]').files
        let customJsonFiles = await getFiles(files);
        //customJsonFiles is an array of your custom files
        console.log(customJsonFiles);
    
    0 讨论(0)
  • 2020-11-22 06:52

    JavaScript btoa() function can be used to convert data into base64 encoded string

    0 讨论(0)
  • 2020-11-22 06:58

    Try the solution using the FileReader class:

    function getBase64(file) {
       var reader = new FileReader();
       reader.readAsDataURL(file);
       reader.onload = function () {
         console.log(reader.result);
       };
       reader.onerror = function (error) {
         console.log('Error: ', error);
       };
    }
    
    var file = document.querySelector('#files > input[type="file"]').files[0];
    getBase64(file); // prints the base64 string
    

    Notice that .files[0] is a File type, which is a sublcass of Blob. Thus it can be used with FileReader.
    See the complete working example.

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