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

250 views Asked by At

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!

2

There are 2 answers

1
Michał Dziwota On BEST ANSWER

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.

3
prosper1 On

Change this line and it should work.

var message = base64Image;

imageData is not 'base64'

Or Upload as File ,Use the file as it is.

var file = imageData
photoRef.put(file).then(snapshot => {
    console.log('Uploaded a blob or file!')
});