angular - 从函数 readDataAsURL() 获取数据时出现问题,而是返回未定义
问题描述
语境
我正在尝试从我的外部存储接收一个图像文件作为 base64,为此我使用了函数 readAsDataURL(),它带有基于File API的Ionic File 插件。我不知道我做错了什么,因为我可以从函数内部的日志中看到 base64 字符串,但我无法正确返回这个字符串,而是收到一个未定义的对象。
我的功能
...
this.uriToBase64(arrayItem2.filePath).then((imageAsBase64) => {
console.log("image as base64: ", imageAsBase64); // Receiving undefined here
});
...
async uriToBase64(uri) {
let nameFile = uri.replace(this.file.dataDirectory, '');
await this.file.readAsDataURL(this.file.dataDirectory, nameFile).then((file64) => {
let fileWithoutExtension = ('' + file64 + '').replace(/^data:image\/(png|jpg|jpeg);base64,/, '');
console.log("File without extension: ", fileWithoutExtension); // Receiving the base64 correctly here
return fileWithoutExtension;
})
.catch(err => {
console.log("Error while transforming image to base64: ", err);
});
}
细节
离子 v4
我认为我使用该功能的方式是正确的,我们可以在这里看到相同的用法。
我发现了一些相关的问题,但它们对我帮助不大:
解决方案
@aaronksaunders在这里回答的问题:
this.uriToBase64(arrayItem2.filePath).then((_result) => {
console.log("image as base64: ", _result); // Receiving the ZoneAwarePromise here
});
uriToBase64(uri) {
let nameFile = uri.replace(this.file.dataDirectory, '');
return this.file.readAsDataURL(this.file.dataDirectory, nameFile).then((file64) => {
let base64String = ('' + file64 + '').replace(/^data:image\/(png|jpg|jpeg);base64,/, '');
console.log("data: ", base64String); // Receiving the base 64 correctly here
return base64String;
})
.catch(err => {
console.log("Error while transforming image to base64: ", err);
return err;
});
}
推荐阅读
- python - 如何在 Django 模板的 for 循环中使用 2dicts?
- javascript - Django/jQuery-从多个按钮获取提交按钮值
- seo - 链接不同页面中的模式标记
- php - 如果按 sql php 排序
- java - Android 跳过了 602 帧!应用程序可能在其主线程上做了太多工作
- amazon-web-services - CloudFormation 创建更改集失败,并显示“模板参数由转换修改”
- java - 如何通过可变参数(程序参数)有条件地排除 Spring bean?
- python - 将 DataArray 插值到新坐标
- python - 如何使用 Xpath 为 selenium 选择锚标记?
- mocha.js - Mochawesome 报告未在浏览器中打开?