Ionic Camera Photo Upload in Firebase

In Ionic, we can upload a file in Firebase as easily as CRUD operation on Firebase through Ionic.  Here our app we are going to see how to take pictures on a mobile device and upload them immediately to Firebase.

What are we Learning?

  1. Uploading taken a photo of the camera to Firebase storage service.
  2. AlertController to display an alert message when we successful upload photo to Firebase Storage.

Step 1: Setting up Apps 

ionic start cameraFirebase blank
$ 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 and click on Add Firebase to your web app. Copy the web app API from firebase project and add  in app.components.ts as 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: "AIUyQ",
        authDomain: "camm",
        databaseURL: "https",
        projectId: "camer",
        storageBucket: "camet.com",
        messagingSenderId: "939"
      };
      
      firebase.initializeApp(firebaseConfig);
    });
  }
}

 

Step 2: Adding user interface for Apps

Add the following code in home.ts file

<ion-header>
  <ion-navbar>
    <ion-title>Ionic Camera Firebase</ion-title>
  </ion-navbar>
</ion-header>
<ion-content padding>
  <div style="display:flex;justify-content:center">
    <button ion-button (click)="capture()">Lets take a picture!</button>
    <img [src]="captureDataUrl" *ngIf="captureDataUrl"/>
    <button ion-button (click)="upload()" *ngIf="captureDataUrl">Upload to Firebase!</button>
  </div>
</ion-content>

 

 

Step 3: Uploading pictures to Firebase

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:

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

Add the following code in home.ts file

import { Component } from '@angular/core';
import { NavController} 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;

  
  constructor(public navCtrl: NavController) {
  }

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

    Camera.getPicture(cameraOptions)
      .then((imageData) => {
        // imageData is either a base64 encoded string or a file URI // If it's base64:
		
        this.captureDataUrl = 'data:image/jpeg;base64,' + imageData;
      }, (err) => {
      // Handle error
	  
    });
  } // End of capture camera


  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!


      });
  }
}

 

 

Note: As in this example, we don’t set any authentication. For access the Firebase storage we have to change to storage rule so that any one can read/write on storage. This means allowing the public to access. Click on storage rule and change the value for public access as

 

Step 4: Show prompt when upload succeeds

We are using AlertControlle component from ionic-angular package and to display alert box for successful uploading a photo to fire base.  To achieve this we have to import

import { NavController, AlertController } from ‘ionic-angular’;

add the function to show alert message
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 = "";
  }

Adding complete code for home.ts

import { Component } 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;
  
  constructor(public navCtrl: NavController, alertCtrl: AlertController) {
    this.alertCtrl = alertCtrl;
  }

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

    Camera.getPicture(cameraOptions)
      .then((imageData) => {
        // imageData is either a base64 encoded string or a file URI
        // If it's base64:
		
        this.captureDataUrl = 'data:image/jpeg;base64,' + imageData;
      }, (err) => {
      // Handle error
	  
    });
  } // End of capture camera


  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 = "";
  }
}