How to upload an image coming from the Ionic's Camera to firebase?

Viewed 927

I've managed to take a picture using Ionic camera API:

  async pickImage(sourceType: CameraSource) {
    const image = await Camera.getPhoto({
      quality: 90,
      allowEditing: true,
      resultType: CameraResultType.Uri,
      source: sourceType,
    });
    console.log(image);
  }

which gives me this:

enter image description here

I've also found that to upload using angular fire storage, but I can't figure out how to connect the two. I don't really understand what are the format in between, what format I should ask to the Camera API and what format should I provide to the AngularFireStorage API.

I tried this:

const filePath = 'name-your-file-path-here';
const ref = this.storage.ref(filePath);
const task = ref.put(image.webPath);
task
  .snapshotChanges()
  .pipe(finalize(() => console.log(ref.getDownloadURL())))
  .subscribe();

But I get this error:

ERROR Error: Uncaught (in promise): FirebaseStorageError: {"code_":"storage/invalid-argument","message_":"Firebase Storage: Invalid argument in `put` at index 0: Expected Blob or File.","serverResponse_":null,"name_":"FirebaseError"}

Your lights would be highly appreciated :)

1 Answers

that "webpath" is not a file or a blob, you need to convert it before you call the put. There is an example of how to convert it on the ionic website

https://ionicframework.com/docs/angular/your-first-app/3-saving-photos

private async readAsBase64(cameraPhoto: CameraPhoto) {
  // Fetch the photo, read as a blob, then convert to base64 format
  const response = await fetch(cameraPhoto.webPath!);
  const blob = await response.blob();

  return await this.convertBlobToBase64(blob) as string;  
}

convertBlobToBase64 = (blob: Blob) => new Promise((resolve, reject) => {
  const reader = new FileReader;
  reader.onerror = reject;
  reader.onload = () => {
      resolve(reader.result);
  };
  reader.readAsDataURL(blob);
});
Related