Ad

How To Set Image Format To Upload To Firebase Storage (Ionic 3)

I am using html input to select an image and a separate button to upload:

<input class="file-upload-button" (change)="changedPhoto($event)" #inputcamera type="file" accept="image/*" capture="camera" />

<button ion-button color="primary" (click)="uploadPicture()">
   Upload
</button>

Here is my typescript to set this.imageSource and pass to provider:

  ionViewDidLoad() {
    const element = this.cameraInput.nativeElement as HTMLInputElement;
    element.onchange = () => {
      const reader = new FileReader();
      reader.onload = (r: any) => {
        //THIS IS THE ORIGINAL BASE64 STRING AS SNAPPED FROM THE CAMERA
        let base64 = r.target.result as string;
        //FIXING ORIENTATION USING NPM PLUGIN fix-orientation
        fixOrientation(base64, { image: true }, (fixed: string, image: any) => {
          //fixed IS THE NEW VERSION FOR DISPLAY PURPOSES
          this.img = fixed;
        });
      };
      reader.readAsDataURL(element.files[0]);
    };
  }

  changedPhoto(event) {
    this.imageSource = event.target.files[0];
  }

  uploadPicture() {
    this.publishedProvider.addPWAPicture(data.imageName, this.itemId, this.itemName, this.imageSource, this.userProfile.id).then(() => {
      this.imageName = '';
      this.imageSource = null;
  });

Lastly, my provider takes this.imageSource and uploads to Firebase storage:

  addPWAPicture(imageName, ItemId, itemName, imageSource, uploaderId): firebase.Promise<any> {
    let TimeStamp = new Date();
    this.items.child('/ItemList').child(ItemId)
    .child('ImageList').push({
      imageName: imageName,
      timestamp: TimeStamp
    })
    .then((newImage) => {
      if (imageSource != null) {
        firebase.storage().ref('/itemPicture/').child(newImage.key)
        .child('imageSource.jpg').putString(imageSource, 'base64', {contentType: 'image/jpeg'})      
      }
    });
  }

My question:

Selecting an image with cordova camera uploads to firebase without error, but using html input, I can preview the image properly, but on upload to firebase, I get the following error. Why doesn't it like the output from filereader?

ERROR Error: Uncaught (in promise): [object Object]
Ad

Answer

Fixed this issue myself - simply use .put() instead of .putString() as the file reader outputs blob, not base64!

Ad
source: stackoverflow.com
Ad