I'm using the Ionic 3 Camera and File plugins to work with image selection from the user's Android gallery app. The plugin returns a file uri which I want to use to extract a base64 encoded image with the File plugin, but I get a NOT_FOUND_ERR when I attempt to read the file from the cache directory. Here's a sample of my code and some log outputs:
this.camera.getPicture(this.getCameraOptionsForPhotoLibrary()).then((fileUri: string) => {
const fileNameIndex: number = fileUri.lastIndexOf('/') + 1;
// file:///storage/emulated/0/Android/data/com.myDomain.myApp/cache/
const cacheDirectoryFromFileUri = fileUri.substring(0, fileNameIndex );
// FB_IMG_1532921240445.jpg?1532982282636
const fileName = fileUri.substring(fileNameIndex);
this.file.readAsDataURL(cacheDirectoryFromFileUri, fileName).then(base64 => {
alert('base64 cacheDirectoryFromFileUri success: ' + JSON.stringify(base64));
}, err => {
alert('base64 cacheDirectoryFromFileUri err: ' + JSON.stringify(err));
});
Please let me know I can provide any more information to help troubleshoot.
I was unable to replicate Patra's answer the way it was described, but I did manage to extract some useful information through testing since I first posted.
In some cases I found if I remove the trailing digits after the ? (FB_IMG_1532921240445.jpg?1532982282636), the result was successfully returned. But this was conditional on a couple of device/configuration scenarios. For instance, it fails on Oreo on a Pixel 2 if I release an APK. In fact, it fails without the error callback being invoked, so I can't even handle the failure. But for some reason if I build from the CLI with the -lc flags on the same device, it will return the base64 result as intended.
When testing a 7.0 and 7.1 emulated device, it works as intended regardless of the build configuration.
It's a frustrating experience that the behavior is markedly different between devices and configurations. I'm especially curious about the livereload discrepancy, if anyone has any insight on why the file plugin behavior changes based on this flag it would be great to know.
I'm still trying to solve this, although apart from cracking open the plugin I'm not sure where to go. I have experimented with the Base64 Native Plugin which seems to work initially, but it doesn't seem to be actively managed and there are a lot of unresolved issues according to the github page. I may end up using a combination of the File and Base64 plugins to get what I need for now.
/** Update **/
A member of our team found the specific answer to our problem here: https://forum.ionicframework.com/t/file-readastext-never-resolves/85375/24
If this link ever breaks, here is what we did to fix it:
Place cordova.js after polyfills.js in index.html
What a horrific bug.