Ionic Uploading Image from Gallery to Firebase

Firebase allows us to upload an image. Here we are learning how to upload a photo from the photo gallery to Firebase server.

 

Step 1: Setting up Apps 

ionic start blank cameraFb
$ ionic cordova plugin add cordova-plugin-camera
$ npm install --save @ionic-native/camera
npm install firebase --save

 

We have to create a project in Firebase for an ionic app we have to select web app. 

 On clicking on the web app we will get API from Firebase project and add this code and import firebase in app.components.ts as a highlight.

import { Component } from '@angular/core';
....

import { HomePage } from '../pages/home/home';
import firebase from 'firebase';

@Component({
  templateUrl: 'app.html'
})
export class MyApp {
  rootPage:any = HomePage;

  constructor(platform: Platform, statusBar: StatusBar, splashScreen: SplashScreen) {    
    platform.ready().then(() => {
      statusBar.styleDefault();
      splashScreen.hide();

      const firebaseConfig = {
        apiKey: "....",
        authDomain: "cam....,
        databaseURL: "h....",
        projectId: "camera.....",
        storageBucket: "camera.....",
        messagingSenderId: "933..."
      };
      
      firebase.initializeApp(firebaseConfig);
    });
  }
}

By default we need authentication to use storage in Firebase, so for this example, we are not using any authentication. We have to change the storage rule as

 

Step 2: Adding user interface for Apps

Add the following code in home.ts file, we will create a button to take an image from the photo gallery.

<ion-header>
  <ion-navbar>
    <ion-title>
      Camera Image Upload
    </ion-title>
  </ion-navbar>
</ion-header>

<ion-content padding>
  <ion-row class="center">
      <button ion-button (click)="getPicture(0)">Show Album</button>  
  </ion-row>
  <ion-card>
    <img [src]="captureDataUrl" *ngIf="captureDataUrl"/>
    <button ion-button (click)="upload()" *ngIf="captureDataUrl">Upload to Firebase!</button>
  </ion-card>
</ion-content>  

 

Step 3:  Adding code for uploading photo to firebase

The getPicture(sourceType) method we are passing zero as an argument, as in camera option, source type zero is for selecting an image from gallery and getPicture(1) for selecting the photo from the camera.

To upload photo, we will first need to get the root storage reference via firebase.storage().ref(). After that, we need to set file path in Firebase Storage. In this app, we have defined that all pictures must be inside a path ./images/filename-.jpg.

Once we have image path reference we will need to do the actual uploading using the
imageref.putString() function.
The function requires 2 parameters, which is the data of the actual picture, and the format of the data.
In the code below, since our picture was captured by the camera and stored inside the captureDataUrl, with the format of DATA_URL, we will need to tell Firebase that we will be uploading in that format:

import { Component, Input } from '@angular/core';
import { NavController, AlertController } from 'ionic-angular';
import { Camera, CameraOptions } from 'ionic-native';
import firebase from 'firebase';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {
  captureDataUrl: string;
  alertCtrl: AlertController;

  @Input('useURI') useURI: Boolean = true;
   
  constructor(public navCtrl: NavController,  alertCtrl: AlertController) {
     this.alertCtrl = alertCtrl;
  }


  getPicture(sourceType){
    const cameraOptions: CameraOptions = {
      quality: 50,
      destinationType: Camera.DestinationType.DATA_URL,
      encodingType: Camera.EncodingType.JPEG,
      mediaType: Camera.MediaType.PICTURE,
      sourceType: sourceType
    };

    Camera.getPicture(cameraOptions)
     .then((captureDataUrl) => {
       this.captureDataUrl = 'data:image/jpeg;base64,' + captureDataUrl;
    }, (err) => {
        console.log(err);
    });
  }  

upload() {
    let storageRef = firebase.storage().ref();
    // Create a timestamp as filename
    const filename = Math.floor(Date.now() / 1000);

    // Create a reference to 'images/todays-date.jpg'
    const imageRef = storageRef.child(`images/${filename}.jpg`);

    imageRef.putString(this.captureDataUrl, firebase.storage.StringFormat.DATA_URL)
      .then((snapshot)=> {
        // Do something here when the data is succesfully uploaded!
        this.showSuccesfulUploadAlert();
    });
  }

  showSuccesfulUploadAlert() {
    let alert = this.alertCtrl.create({
      title: 'Uploaded!',
      subTitle: 'Picture is uploaded to Firebase',
      buttons: ['OK']
    });
    alert.present();
    // clear the previous photo data in the variable
    this.captureDataUrl = "";
  }
}

 

Add the camera provider in app.module.ts file

import { BrowserModule } from '@angular/platform-browser';
....
import { Camera } from 'ionic-native';

import { MyApp } from './app.component';
import { HomePage } from '../pages/home/home';

@NgModule({
  declarations: [
    MyApp,
    HomePage
  ],
  imports: [
    BrowserModule,
    IonicModule.forRoot(MyApp)
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp,
    HomePage
  ],
  providers: [
    StatusBar,
    SplashScreen,
    {provide: ErrorHandler, useClass: IonicErrorHandler},
    Camera
  ]
})
export class AppModule {}