Ionic Camera file_uri convert to blob for s3 upload

1.3k Views Asked by At

I am working on a functionality, where I am uplaoding an image after capturing it from native camera. But there's a problem on converting file_uri to blob. It doesn't proceed to readAsArrayBuffer. Any other solutions for converting file_uri to blob?

fileUriToBlob(imageData) {
    return new Promise((resolve, reject) => {
      let fileName = "";
      this.file
        .resolveLocalFilesystemUrl(imageData)
        .then(fileEntry => {
          let { name, nativeURL } = fileEntry;

          // get the path..
          let path = nativeURL.substring(0, nativeURL.lastIndexOf("/"));
          console.log("path", path);
          console.log("fileName", name);

          fileName = name;

          // we are provided the name, so now read the file into a buffer
          return this.file.readAsArrayBuffer(path, name);
        })
        .then(buffer => {
          // get the buffer and make a blob to be saved
          let imgBlob = new Blob([buffer], {
            type: "image/jpeg"
          });
          console.log(imgBlob.type, imgBlob.size);

          // pass back blob and the name of the file for saving
          // into fire base
          resolve({
            fileName,
            imgBlob
          });
        })
        .catch(e => reject(e));
    });
  }

source: https://github.com/aaronksaunders/ionic4-firebase-storage

EDIT:

Tried this

imageToBlob(b64Data: string, contentType: string, sliceSize: number = 512) {
    contentType = contentType || '';
    sliceSize = sliceSize || 512;

    let byteCharacters = atob(b64Data.replace(/^data:image\/(png|jpeg|jpg);base64,/, ''));
    let byteArrays = [];

    for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
      let slice = byteCharacters.slice(offset, offset + sliceSize);

      let byteNumbers = new Array(slice.length);
      for (let i = 0; i < slice.length; i++) {
        byteNumbers[i] = slice.charCodeAt(i);
      }

      let byteArray = new Uint8Array(byteNumbers);
      byteArrays.push(byteArray);
    }
    this.blobImage = new Blob(byteArrays, { type: contentType });
    return this.blobImage;
  }

But I faced this error: DOMException: Failed to execute 'atob' on 'Window': The string to be decoded is not correctly encoded.

1

There are 1 best solutions below

0
Aaron Saunders On

You need to make sure you have installed the cordova-plugin-file

See Ionic documentation - https://ionicframework.com/docs/native/file