How to Upload an Image to Firebase?

Firebase is a popular tool that helps you build apps fast, without managing infrastructure. It offers lots of services to help your app grow such as Hosting, Storage, Database, Authentication and much more. It's built on Google infrastructure and can scale automatically, so you don't have to worry about scaling your own servers.

In this Ionic Framework tutorial I'll show you how to upload an image from an Ionic App to the Firebase Cloud Storage.

Cloud Storage is built for app developers who need to store and serve user-generated content, such as photos, videos or files. Cloud Storage stores your files in a Google Cloud Storage bucket, making them accessible through both Firebase and Google Cloud. This allows you the flexibility to upload and download files from mobile clients via the Firebase SDKs, and do server-side processing such as image filtering or video transcoding using Google Cloud Platform.

Handling images and files is super useful if you want to build rich media content into your apps. For example you could use it to store pictures or videos uploaded to your app by your users. If you learn how to create an Ionic application with Firebase you will be able to build a complete mobile app.

In this ionic tutorial we will mainly use three plugins:

  • Angular Fire for the communication between the Ionic app and the Firebase Database
  • Image Picker to retrieve images from the phone's image gallery within our ionic app
  • Crop to allow users to crop an image once it has been selected from the image gallery

Let's start with an Ionic app. You can either download the free ionic example app we built for this tutorial by clicking in the "GET THE CODE" button from above or you can create your own ionic app from scratch. To learn more about how to start with Ionic Framework I suggest you to read Ionic Framework introduction and key components.

To install the plugins mentioned before, we need to run the following commands in our development console.

angularfire plugin:

npm install firebase angularfire2 --save

Ionic ImagePicker plugin:

ionic cordova plugin add cordova-plugin-telerik-imagepicker --variable PHOTO_LIBRARY_USAGE_DESCRIPTION="your usage message"

npm install --save @ionic-native/image-picker

Ionic Crop plugin:

ionic cordova plugin add cordova-plugin-crop

npm install --save @ionic-native/crop

Connect your Ionic App with Firebase

Once the plugins are installed we need to create a Firebase project (which is free!). To do this we hav to go to the Firebase console, which will take us to the following menu:

Firebase console

At this point you should click on "Add Firebase to your web app" so you will see the credentials of your Firebase app. You will see something like this:

Firebase App credentials

The next step is to add these credentials to your Ionic project. To do so, go to the environment.ts file from your ionic app located at src/environment/ and add the following code:

export const environment = {
  production: false,
  firebase: {
    apiKey: "YOUR_API_KEY",
    authDomain: "YOUR_AUTH_DOMAIN",
    databaseURL: "YOUR_DATABASE_URL",
    projectId: "YOUR_PROJECT_ID",
    storageBucket: "YOUR_STORAGE_BUCKET",
    messagingSenderId: "YOUR_MESSAGING_SENDER_ID"
  }
}

Keep in mind that you have to replace the constants with your values.

Congratulations! We've ended the installation process. At this point we're ready to move on to the implementation.

Ionic Firebase Storage

In our ionic firebase example we've created a super simple Ionic 3 app which has only two buttons; one to pick an image from the image gallery and save it to the Firebase database; and the other one, with the additional feature that allows to crop the image (using the Crop plugin) and then save it to Firebase.

Firebase Ionic App

In order to perform the operations related to the interaction with the Firebase database, we'll create a service in our ionic app that we'll call FirebaseService.

Within this service we'll create an uploadImage method that will receive the URI provided to us by the ImagePicker plugin and we'll save the image to Firebase Storage.

uploadImage(imageURI){
  return new Promise<any>((resolve, reject) => {
    let storageRef = firebase.storage().ref();
    let imageRef = storageRef.child('image').child('imageName');
    this.encodeImageUri(imageURI, function(image64){
      imageRef.putString(image64, 'data_url')
      .then(snapshot => {
        resolve(snapshot.downloadURL)
      }, err => {
        reject(err);
      })
    })
  })
}

Firebase Storage is a tool provided by Firebase to save files; it's independent from both Firebase Realtime database and Firestore.

Within the uploadImage function we have the following:

  • storageRef represents a reference to the Storage root.
  • imageRef is the reference to a Storage lower-tier location, used by the child() method in a specific reference. That's why the images we upload to Firebase will be stored in the image folder.
  • encodeImageUri() is a function we'll explain below that is used to transform a URI into a base64 URL.
  • imageRef.putString() is the function to upload the base64 URL string to the storage. Once our Firebase image is uploaded it returns the target URL of the uploaded image.

Another thing to keep in mind is that we must transform the URI into a base64 URL. To do so, we created the following function that we called from the previous function uploadImage().

encodeImageUri(imageUri, callback) {
  var c = document.createElement('canvas');
  var ctx = c.getContext("2d");
  var img = new Image();
  img.onload = function () {
    var aux:any = this;
    c.width = aux.width;
    c.height = aux.height;
    ctx.drawImage(img, 0, 0);
    var dataURL = c.toDataURL("image/jpeg");
    callback(dataURL);
  };
  img.src = imageUri;
};

Store Images on Firebase Storage with Ionic Framework

Now let's see how to use the previous code from our ionic pages. We will see what happens when clicking our buttons from our super simple ionic example code.


If you're looking for a super complete Ionic app with a bunch of features and components, I suggest you to take a look at Ion2FullApp ELITE - The most complete Ionic 3 Starter App. It will save you lots of development time and it also has many Firebase features.

These are some of the Ionic pages you can find in the Firebase Integration section of Ion2FullApp ELITE.

The functionalities of this firebase integration include: authentication with different providers, feed with search filters, profile page with image handling (for profile picture) and all the CRUD operations.

Ion2FullApp Ionic Firebase Authentication
Ion2FullApp Firebase Ionic
Ion2FullApp Firebase CRUD

Let's begin by the method for choosing an image but without using the option to crop it:

openImagePicker(){
  this.imagePicker.hasReadPermission().then(
    (result) => {
      if(result == false){
        // no callbacks required as this opens a popup which returns async
        this.imagePicker.requestReadPermission();
      }
      else if(result == true){
        this.imagePicker.getPictures({
          maximumImagesCount: 1
        }).then(
          (results) => {
            for (var i = 0; i < results.length; i++) {
              this.uploadImageToFirebase(results[i]);
            }
          }, (err) => console.log(err)
        );
      }
    }, (err) => {
      console.log(err);
    });
  }

As we can see, the result of the imagePicker plugin is a list of images that can be limited by the “maximumImagesCount” property. In this example the limit was just one picture.

Once the photo is chosen, another method is called and it interacts with our FirebaseService to then upload the image to Firebase Storage:

uploadImageToFirebase(image){
  image = normalizeURL(image);

  //uploads img to firebase storage
  this.firebaseService.uploadImage(image)
  .then(photoURL => {

    let toast = this.toastCtrl.create({
      message: 'Image was updated successfully',
      duration: 3000
    });
    toast.present();
    })
  }

normalizeURL is a method used to normalize the absolute URL of the image so that it works in every device. You can read more about this method right here.

Congratulations! You've just learned how to upload an image to Firebase Storage from your Ionic app. In the following image you can verify it has been correctly uploaded to our "image" folder.

Firebase Storage

Now let's crank it up a notch and use the Crop plugin. The Ionic Crop plugin allows us to easily crop an image from our Ionic framework app.

The code is very simple and similar to the previous step, the difference is that once the image is selected using the image picker plugin, we use the crop plugin, which returns the cropped image that we'll upload to Storage.

openImagePickerCrop(){
  this.imagePicker.hasReadPermission().then(
    (result) => {
      if(result == false){
        // no callbacks required as this opens a popup which returns async
        this.imagePicker.requestReadPermission();
      }
      else if(result == true){
        this.imagePicker.getPictures({
          maximumImagesCount: 1
        }).then(
          (results) => {
            for (var i = 0; i < results.length; i++) {
              this.cropService.crop(results[i], {quality: 75}).then(
                newImage => {
                  this.uploadImageToFirebase(newImage);
                },
                error => console.error("Error cropping image", error)
              );
            }
          }, (err) => console.log(err)
        );
      }
    }, (err) => {
      console.log(err);
    });
  }

Keep learning Ionic and Firebase

In this tutorial we've learned how to upload files from our Ionic app to Firebase Storage. Besides, as an additional feature we learned how to crop the selected image.

If you want to learn more about image handling in your Ionic app, I would recommend the following guide Image handling in an Ionic 3 app.

If you want to learn how to send data from a form made in an Ionic 3 application to a Cloud Firestore database you should read Setting up a Database for an Ionic App with Firebase.

If you wish to keep learning about Firebase stay tuned for upcoming tutorials in which I'll be writing about how to make the CRUD operations using Cloud Firestore. You can subscribe to our newsletter by clicking on this link to get noticed when the ionic tutorials are available.

I hope this ionic firebase tutorial was helpful for you. If you have any questions don't hesitate to leave a comment on the section below.

Would you like to keep learning about Ionic Framework? Find dozens of ionic framework tutorials in our tutorials section.