How to convert file to base64 in JavaScript?

前端 未结 7 1936
醉话见心
醉话见心 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: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.

提交回复
热议问题