首页 > 解决方案 > 从函数 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

我认为我使用该功能的方式是正确的,我们可以在这里看到相同的用法。

我发现了一些相关的问题,但它们对我帮助不大:

标签: angularcordovaasynchronousionic-frameworkbase64

解决方案


@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;
    });     
}

推荐阅读