如何在 JavaScript 中将文件转换为 base64?

2022-01-21 00:00:00 base64 javascript

UPDTypeScript 版本也可在答案中找到

UPD TypeScript version is also available in answers

现在我通过这一行获取 File 对象:

Now I'm getting File object by this line:

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

我需要通过base 64中的json发送这个文件.我应该怎么做才能将它转换为base64字符串?

I need to send this file via json in base 64. What should I do to convert it to base64 string?

推荐答案

现代 ES6 方式 (async/await)

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

更新:

如果你想捕捉错误

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;
   }
   //...
}

相关文章