gpt4 book ai didi

javascript - 将文件输入转换为 Base 64 后返回错误

转载 作者:行者123 更新时间:2023-12-03 00:07:50 25 4
gpt4 key购买 nike

根据How to convert the file to base64 in JavaScript?我找到了一种在基于 javascript 的图像中将图像转换为 Base64 的方法,如下所示:

//My Converter Function
function getBase64(file) {
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function () {
console.log("befor");
console.log(reader.result);
console.log("after");
};
reader.onerror = function (error) {
console.log('Error: ', error);
};
}

我使用它的方式是:

getBase64(file).then(
data => (Image64bit = data)

似乎我得到了 64 位字符串,但我每次都会返回此错误:(请注意,如果没有“then”,它不会返回任何内容)

zone.js:192 Uncaught TypeError: Cannot read property 'then' of undefined at UploadFileAndGetUrl (doctors.js:14949) at HTMLButtonElement. (doctors.js:14703) at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:421) at Zone.push../node_modules/zone.js/dist/zone.js.Zone.runTask (zone.js:188) at ZoneTask.push../node_modules/zone.js/dist/zone.js.ZoneTask.invokeTask [as invoke] (zone.js:496) at invokeTask (zone.js:1540) at HTMLButtonElement.globalZoneAwareCallback (zone.js:1566)

befor

doctors.js:14992 data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAyAAAAH0CAMAAADynrlKAAACBFBMVEUAzG9U1pBn2Zskz3vV8+H////g9umH4K71/Pjr+fHJ8Nm97dE/04aj5sCW47d43aSw6sg1143j+e801owDzXHS9ubQ9uRm4..... doctors.js:14993

after

如何解决此错误?

最佳答案

zone.js:192 Uncaught TypeError: Cannot read property 'then' of undefined at

函数getBase64不返回Promise

您需要更正 getBase64,使其返回 Promise 并在 reader.onload 内部解析,值为 reader.result:

function getBase64(file) {
return new Promise(resolve, reject) => {
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function () {
console.log("befor");
console.log(reader.result);
console.log("after");
resolve(reader.result);
};
reader.onerror = function (error) {
console.log('Error: ', error);
reject(error);
};
}
}

关于javascript - 将文件输入转换为 Base 64 后返回错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54883041/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com