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

瓦西里(Vassily):

现在,我通过此行获取File对象:

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

我需要在base 64中通过json发送此文件。如何将其转换为base64字符串?

德米特里·瓦西里耶夫(Dmitry Vasiliev):

现代ES6方式(异步/等待)

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:

如果您想捕捉错误

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如何在React中将文件转换为Base64

如何在客户端javascript中将.wav文件从url转换为base64?

如何在JavaScript中将base64 WAV转换为base64 mp3

如何在java中将图标转换为base64

如何在Azure中将pdf转换为base64

如何在C中将图像转换为base64?

如何在 Flutter 中将图像转换为 Base64

如何在Ionic 3中将视频文件从ios转换为base64

如何在Angular中将本地图像文件转换为base64?

如何在颤振中将图像文件转换为 base64 字符串?

如何在javascript中将Base64文件转换为实际文件/原始文件并将其下载到客户端

在Java中将base64转换为Excel文件

在JavaScript中将base64转换为Blob

在ReactJS / Javascript中将Base64转换为PDF文件时遇到错误

如何在jQuery中将预加载的图像转换为base64数据

如何在 Dart 中将 base64 字符串 url 解码或转换为 UintList?

如何在PHP中将base64转换为十六进制?

如何在Java中将Image转换为base64字符串?

如何在 Expo React Native 中将 base64 转换为字节?

如何在Rust中将十六进制值转换为Base64

如何在 Oracle 中将十六进制值转换为 Base64?

如何在React Native中将字符串转换为base64?

如何在Crypto ++中将base64转换为Integer?

如何在Groovy脚本中将十六进制转换为base64格式

如何在 swift 3 中将 UIImage 数组转换为 base64 数组?

如何在Qt中将QPixmap转换为base64 QString?

如何在 Ionic 中将 base64 字符串转换为 JPG 或 Png

React Native-如何在Android中将图像转换为Base64,反之亦然

如何在PHP中将m3u8转换为base64编码?