猿问

如何在脚本中将文件正确上传为 base64

我试图在javascript中上传文件作为base64,但它抛出了错误。


TypeError: FileReader.readAsDataURL: Argument 1 does not implement interface Blob.

这是代码


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

  <button id="button">upload</button>



document.getElementById('button').addEventListener('click', function() {

  var files = document.getElementById('file').files;


  var reader = new FileReader();

   reader.readAsDataURL(files);

   reader.onload = function () {

     console.log(reader.result);

    alert('my file: ' +reader.result);

   };

   reader.onerror = function (error) {

     console.log('Error: ', error);

   }


});


桃花长相依
浏览 69回答 1
1回答

蝴蝶刀刀

const toBase64 = file => new Promise((resolve, reject) => {&nbsp; &nbsp; const reader = new FileReader();&nbsp; &nbsp; reader.readAsDataURL(file);&nbsp; &nbsp; reader.onload = () => resolve(reader.result);&nbsp; &nbsp; reader.onerror = error => reject(error);});async function Main() {&nbsp; &nbsp;const file = document.querySelector('#myfile').files[0];&nbsp; &nbsp;console.log(await toBase64(file));}Main();
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答