Context
I’m trying to receive an image file from my external storage as base64, to do this I’m using the function readAsDataURL(), that comes with the Ionic File plugin, which is based in File API. I don’t know what I’m doing wrong, because I can see the base64 string from the log inside the function, but I can’t return this string correctly, instead I’m getting what I suppose to be a Promise object (ZoneAwarePromise)
My Function
...
let imageAsBase64 = this.uriToBase64(arrayItem2.filePath).then(() => {
console.log("image as base64: ", imageAsBase64); // Receiving the ZoneAwarePromise 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 base 64 correctly here
return fileWithoutExtension;
})
.catch(err => {
console.log("Error while transforming image to base64: ", err);
});
}
Details
I think the way I’m using the function is correct, we can see the same usage here.
I found some related questions, but they don’t helped me much:
Problem with Ionic Capacitor, pretty similar to my problem
Ionic storage problem, returning ZoneAwarePromise too
StackOverflow similar question
Attempts
Attempt 1
Changing the first part to:
...
this.uriToBase64(arrayItem2.filePath).then((imageAsBase64) => {
console.log("image as base64: ", imageAsBase64);
});
...
stops the error ZoneAwarePromise error, but I still can’t receive the data. Receiving undefined
instead.
Attempt 2
While changing the async syntax to an Obsevable function I still get an ZoneAwarePromise object, but at least now the value inside (__zone_symbol__value) contain the base64 string I want. So how do I receive this data correctly and not this Promise object?
uriToBase64(uri): Observable<any> {
let nameFile = uri.replace(this.file.dataDirectory, '');
let output = 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);
return fileWithoutExtension;
})
.catch(err => {
console.log("Error while transforming image to base64: ", err);
});
return of(output);
}