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;
}
//...
}
这篇关于如何在 JavaScript 中将文件转换为 base64?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!