Search code examples
angularfirebaseionic4firebase-storageionic-devapp

How to upload photo taken on phone through devapp on firebase storage in Ionic 4


I am trying to upload a photo taken through my phone's camera (With Ionic 4 Native Camera Plugin through DevApp) and upload it to Firebase Storage. Now I am able to take the photo, but when I upload it, the console does not throw any errors and just does not do anything. In the end, the photo is not uploaded to the firebase storage.

Here are my codes:

.html:

<ion-button (click)="takePicture()"></ion-button>

.ts:

  takePicture(){
    const options: CameraOptions = {
      quality: 100,
      destinationType: this.camera.DestinationType.FILE_URI,
      encodingType: this.camera.EncodingType.JPEG,
      mediaType: this.camera.MediaType.PICTURE
     }

     this.camera.getPicture(options).then((imageData) => {
       var storage = firebase.storage().ref();
       var photoRef = storage.child('Manager Images'); 
       console.log(photoRef); <-- This reference is correct

       let base64Image = 'data:image/jpeg;base64,' + imageData;
       console.log(base64Image); <-- Returns "data:image/jpeg;base64,file:///storage/emulated/0/Android/data/io.ionic.devapp/cache/1577622281686.jpg"

       // Base64 formatted string
       var message = imageData;
       photoRef.putString(message , 'base64', { contentType: 'image/jpg' }).then((savedPicture) => {
       console.log(savedPicture.downloadURL);
});


   }, (err) => {
    // Handle error
   });
  }

Am I doing something wrong with the .putString method? I referred to https://firebase.google.com/docs/storage/web/upload-files for the guidelines but I still can't get this to work. Please help!


Solution

  • Change destination type to this.camera.DestinationType.DATA_URL to get base64 and then put it into firebase storage.

      takePicture(){
        const options: CameraOptions = {
          quality: 100,
          destinationType: this.camera.DestinationType.DATA_URL,
        ...
    
    

    PS. be sure if let base64Image = 'data:image/jpeg;base64,' + imageData; is necessarily or if imageData already has coded type in base64 format.