Convert File URI to Blob

I’m attempting to use cordova-plugin-camera to retrieve an image and upload it to Firebase. Many common solutions use the Base64 format to do so but I would like to avoid that in light of performance issues and use File URI instead.

The best solution for Android I’ve seen for this is as follows:

makeFileIntoBlob(_imagePath) {
return new Promise((resolve, reject) => {
        window.resolveLocalFileSystemURL(_imagePath, (fileEntry) => {

          fileEntry.file((resFile) => {

            var reader = new FileReader();
            reader.onloadend = (evt: any) => {
              var imgBlob: any = new Blob([evt.target.result], { type: 'image/jpeg' });
              imgBlob.name = 'sample.jpg';
              resolve(imgBlob);
            };

            reader.onerror = (e) => {
              console.log('Failed file read: ' + e.toString());
              reject(e);
            };

            reader.readAsArrayBuffer(resFile);
          });
        });
      });
    }

I think there have been some updates to the cordova-plugin-file for Ionic so that I now perform:

makeFileIntoBlob(imagePath) {
    this.file.resolveLocalFilesystemUrl(imagePath).then((fileEntry) => {
      fileEntry.file //Not a method
    }, (err) => {
      console.log("Put error message here");
    })
  }

as resolveLocalFilesystemUrl now returns a promise. The returned FileEntry appears to have almost every method available except .file() which I need to complete the conversion to Blob. Is there anyway to fix this or any other ways to do this?

Many Thanks

Some lack of thinking on my part but found the solution thanks to:

https://stackoverflow.com/questions/41536303/cannot-read-a-file-using-cordova-file-plugin-in-an-ionic-2-project

In Typescript the resolveLocalFilesystemUrl method was returning an Entry, not a FileEntry so you just have to specify fileEntry as type any and it will work.

Hope this helps anyone that needs it :slight_smile:

1 Like

If it’s a FileEntry, cast it to a FileEntry. any completely blows up any type-based assistance your development environment or build tools would be able to give you.

1 Like

Very true. I think as I was using it for a single method I felt comfortable doing so, but you are definitely correct in specifying its type :+1: