Javascript Promises with FileReader()

前端 未结 6 1860
滥情空心
滥情空心 2020-12-05 00:25

I have the following HTML Code:


And Here\'s my JS Code:

var inputFiles = document.getE         


        
6条回答
  •  萌比男神i
    2020-12-05 01:25

    Here is another modification to Jens' answer (piggybacking off Mido's answer) to additionally check the file size:

    function readFileBase64(file, max_size){
            max_size_bytes = max_size * 1048576;
            return new Promise((resolve, reject) => {
                if (file.size > max_size_bytes) {
                    console.log("file is too big at " + (file.size / 1048576) + "MB");
                    reject("file exceeds max size of " + max_size + "MB");
                }
                else {
                var fr = new FileReader();  
                fr.onload = () => {
                    data = fr.result;
                    resolve(data)
                };
                fr.readAsDataURL(file);
                }
            });
        }
    

提交回复
热议问题