Firebase File Upload using Ionic

ionic-firebase-upload-images

Let's learn how to upload files to firebase cloud storage using ionic 2 / 3 without using any plugins.before we starting, we need to rewrite rules for firebase project.

Note: For a testing purpose, I have updated firebase rule as open, which means anyone can access your firebase storage with your credentials.

Let's create new project & add required dependencies

ionic start firebasefileupload blank
cd firebasefileupload

ionic cordova platform add android
ionic cordova platform add ios

npm install --save firebase

We need to initiate firebase inside constructor from app.component.ts then, we need to work with other files

firebase.initializeApp({
    apiKey: "xxxx",
    authDomain: "xxx",
    databaseURL: "xxx",
    projectId: "xxx",
    storageBucket: "xxx",
    messagingSenderId: "xxx"
});

Working with home.html

<ion-content padding>
    Uploaded File: <a *ngIf="this.url" href="{{this.url}}">{{this.url}}</a>

    <button ion-button (click)="chooseFile()">Upload Image</button>
    <input style="display: none;" id="image" name="image" type="file" (change)="upload()">
</ion-content>

here we have created a html input button with hidden mode & created ionic button for user action.once user click that button,   we're calling input="file" type for choosing files. After choosing files, we're calling firebase storage for uploading

Working with home.ts

chooseFile() {
  // open file picker
  document.getElementById('image').click();
}
upload() {
  // Create a root reference
  let storageRef = firebase.storage().ref();
  let loading = this.loadingCtrl.create({ content: 'Please wait...' });
  loading.present();

  for (let selectedFile of [(document.getElementById('image')).files[0]]) {
    let path = '/files/' + Date.now() + `${selectedFile.name}` ;
    let iRef = storageRef.child(path);
    iRef.put(selectedFile).then(() => {
      loading.dismiss();
      iRef.getDownloadURL().then( url => this.url = url )
    });
    
  }
}

Here, we have used firebase.storage().ref() also we're setting a path for /files/currenttime/filename .once file is uploaded, we're getting downloadable url & assigned to this.url variable

Download latest Source code