How to upload an image to Firebase from an Ionic 4 app?

firebase Jun 24, 2019

We as a whole realize that Firebase works admirably with regards to realtime databases. In any case, did you realize that Firebase is likewise extraordinary for transferring information and records to your application's private Firebase Storage?

In this Ionic 4 Framework instructional exercise, I'll tell you the best way to transfer a picture from an Ionic application to the Firebase Storage.

As we all know this is always usefull for any application as we upload profile image like wise so how upload image works and what all things we need to know?We will see all this in this tutorial and will explain everything in detail...

So, to connect firebase to ionic project we need to create firebase project

1) Go to https://console.firebase.google.com/u/0/

Your console will look something like this

2) Click on create a project button and make a project as soon as you make a project you will be redirected to dashboard page of your project

3) Now Click On </> icon to make web project Now give a name to app and click on register button. You will get the firebase sdk config now copy the content of script tag started from firebaseConfig ={} and keep somewhere safe.

4) Now click on continue to console button.

5) You have successfully created your firebase project.

6) Now create the ionic project with command

ionic start <NAME-OF-YOUR-APPLICATION> --blank 

7) The above command will create the ionic project for you.

8) As your project get's created open it in editor.I will be using vscode.

9) Now first thing we need to do is paste the config which we save somewhere in environment.ts in src/environment/environment.ts

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

10) Now install angular fire to use firebase in ionic project using npm.

npm install firebase angularfire2 --save

11) Now in your app.module.ts  let's import angular firebase modules ,

12) Now in your home.html component lets add button and preview for file

<ion-header>
  <ion-toolbar>
    <ion-title>
      Image Preview
    </ion-title>
  </ion-toolbar>
</ion-header>

<ion-content padding>
  <div class="box">
    <div class="preview">
      <img [src]="url" alt="">
    </div>
    <div class="uploadbtn">
      <label>
        <input (change)="uploadImage($event)" type="file" class="image-upload" accept="image/*">
      </label>
    </div>
  </div>
</ion-content>

Now let's add some css

.box {
    display: block;
    min-width: 300px;
  
    margin: 10px;
    background-color: white;
    border-radius: 5px;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.12), 0 1px 2px rgba(0, 0, 0, 0.24);
    transition: all 0.3s cubic-bezier(0.25, 0.8, 0.25, 1);
    overflow: hidden;

    & .preview {
      
        width: 100%;
        position: relative;
        overflow: hidden;
        text-align: center;
        background-color: white;
        background-position: center center;
        background-repeat: no-repeat;
        background-size: cover;
    }

    & .uploadbtn {
        position: relative;
        height: 75px;
        background-color: rgb(125, 95, 160);
        cursor: pointer;
        overflow: hidden;
        text-align: center;
        transition: background-color ease-in-out 150ms;

        & label {
            display: flex;
            align-items: center;
            width: 100%;
            height: 100%;
            font-weight: 400;
            text-overflow: ellipsis;
            white-space: nowrap;
            cursor: pointer;
            overflow: hidden;

            & input {
                width: 0.1px;
                height: 0.1px;
                opacity: 0;
                overflow: hidden;
                position: absolute;
                z-index: -1;
            }


            &::after {
                content: 'add';
                font-family: 'Material Icons';
                position: absolute;
                line-height: 2;
                font-size: 2.5rem;
                color: #e6e6e6;
                top: calc(50% - 2.5rem);
                left: calc(50% - 1.25rem);
                z-index: 0;
                }
            }
        }
    }

14 ) Now lets make the uploadImage($event) function in home.page.ts

import { Component } from '@angular/core';
import { AngularFirestore } from '@angular/fire/firestore';
import { AngularFireStorage } from '@angular/fire/storage';

export interface Image {
  id: string;
  image: string;
}
@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss'],
})
export class HomePage {
  url: any;
  newImage: Image = {
    id: this.afs.createId(), image: ''
  }
  loading: boolean = false;;

  constructor(private afs: AngularFirestore, private storage: AngularFireStorage) { }

  uploadImage(event) {
    this.loading = true;
    if (event.target.files && event.target.files[0]) {
      var reader = new FileReader();
     
      reader.readAsDataURL(event.target.files[0]);
      // For Preview Of Image
      reader.onload = (e:any) => { // called once readAsDataURL is completed
        this.url = e.target.result;
      
        // For Uploading Image To Firebase
        const fileraw = event.target.files[0];
        console.log(fileraw)
        const filePath = '/Image/' + this.newImage.id + '/' + 'Image' + (Math.floor(1000 + Math.random() * 9000) + 1);
        const result = this.SaveImageRef(filePath, fileraw);
        const ref = result.ref;
        result.task.then(a => {
          ref.getDownloadURL().subscribe(a => {
            console.log(a);
            
            this.newImage.image = a;
            this.loading = false;
          });

          this.afs.collection('Image').doc(this.newImage.id).set(this.newImage);
        });
      }, error => {
        alert("Error");
      }

    }
  }



  SaveImageRef(filePath, file) {

    return {
      task: this.storage.upload(filePath, file)
      , ref: this.storage.ref(filePath)
    };
  }
}

In the above ts file we have created an interface of what all thing will be saved with image so we are just saving image with id so the interface will look something like this.

export interface Image {
  id: string;
  image: string;
}

After that we have imported (angularfirestore ) and (angularfirestorage ) for storing images.

In the upload function first with the help of filereader we are getting the content of file through reader function that is readDataAsURL with which we preview image.

After that we are getting the fileraw and making the filepath where the image will be stored so that we can easily get image from database.

Now We have made one more function save saveImageRef which we save image to firebase storage and return the reference where the file is store and the downloadUrl of the file so that you can easily pass downloadUrl to database.

So this is how our application looks like

That's all ,  we are done with uploading image to firebase database.

Abhishek

Hi There! I Am Abhishek Developer, Singer & Photographer. Living In Mumbai. My interests range from technology to entrepreneurship. I am also interested in food, designing, and education.