Upload Angular Multiple Images using Firebase Database

"Angular Firebase tutorial – Upload multiple images using Firebase Database with step-by-step code"

Upload Angular Multiple Images using Firebase Database is a powerful and common feature required by many web applications — from photo galleries to product catalogs. In this guide you’ll learn step-by-step how to set up an Angular project, integrate Firebase, and implement multiple image upload with progress tracking and Firestore storage.


Introduction

This tutorial shows how to upload multiple images from an Angular app to Firebase and save file metadata (name + download URL) in Firestore. We’ll keep your provided code unchanged and pack it into an SEO-friendly article with headings (H2/H3), bullet lists, and example Yoast SEO settings.

Prerequisites

  • Node.js and npm installed
  • Angular CLI installed
  • Firebase account (project created)
  • Basic knowledge of Angular components and services

Step-by-step Implementation

Here’s the full article with your original code — I’ll provide the entire content here in chat so you can copy-paste easily (instead of inside the canvas where code is harder to copy).


Upload Angular Multiple Images using Firebase Database

Title (Main Keyword): Upload Angular Multiple Images using Firebase Database

Intro (first 100 words must include the keyword):
Upload Angular Multiple Images using Firebase Database is a powerful and common feature required by many web applications — from photo galleries to product catalogs. In this guide you’ll learn step-by-step how to set up an Angular project, integrate Firebase, and implement multiple image upload with progress tracking and Firestore storage.


Step-by-step Implementation

Step-1. Create a new Angular Project

ng new UploadImageApp

Step-2. Install firebase inside your App folder

cd UploadImageApp
npm install angularfire2 firebase --save

Step-3. Firebase Configuration (environments.ts)

export const environment = {
  production: false,
  firebaseConfig : {
   apiKey: "",
   authDomain: "",
   databaseURL: "",
   projectId: "",
   storageBucket: "",
   messagingSenderId: "",
   appId: "",
   measurementId: ""
  }
}

Step-4. Update app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { environment } from '../environments/environment';
import { AngularFireModule } from 'angularfire2';
import { AngularFirestoreModule } from 'angularfire2/firestore';
import { AngularFireStorageModule } from 'angularfire2/storage';
import { DropZoneDirective } from './drop-zone.directive';
import { FileUploadComponent } from './file-upload/file-upload.component';
import { FileSizePipe } from './file-size.pipe';
import { RouterModule, Routes } from '@angular/router';
import { LoginComponent } from './login/login.component';
import { FormsModule } from '@angular/forms';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { CustomMaterialModule } from './core/material.module';
import { UploadFormComponent } from './upload-form/upload-form.component';

const approaches: Routes = [
  { path: 'file-upload', component: FileUploadComponent },
  { path: '', redirectTo: '/file-upload', pathMatch: 'full' },
];

@NgModule({
  declarations: [
    AppComponent,
    DropZoneDirective,
    FileUploadComponent,
    FileSizePipe,
    LoginComponent,
    UploadFormComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    AngularFireModule.initializeApp(environment.firebaseConfig),
    AngularFirestoreModule,
    AngularFireStorageModule,
    FormsModule,
    BrowserAnimationsModule,
    CustomMaterialModule,
    RouterModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Step-5. Update app-routing.module.ts

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { FileUploadComponent } from './file-upload/file-upload.component';
import { LoginComponent } from './login/login.component';

const routes: Routes = [
  { path: 'file-upload', component: FileUploadComponent },
  { path: '', redirectTo: '/file-upload', pathMatch: 'full' },
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

Step-6. Generate Upload Form Component

ng g component upload-form

Step-7. File Upload Component (file-upload.component.ts)

import { Component, OnInit } from '@angular/core';
import { AngularFireStorage, AngularFireUploadTask } from 'angularfire2/storage';
import { Observable } from 'rxjs/Observable';
import { AngularFirestore } from 'angularfire2/firestore';
import { tap, finalize } from 'rxjs/operators';
import { Router } from '@angular/router';
import { map } from 'rxjs/operators';
import * as firebase from 'firebase';
import { combineLatest } from 'rxjs';

@Component({
  selector: 'file-upload',
  templateUrl: './file-upload.component.html',
  styleUrls: ['./file-upload.component.scss'],
})
export class FileUploadComponent implements OnInit {
  uploads: any[];
  allPercentage: Observable<any>;
  files: Observable<any>;

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

  ngOnInit() {
    this.files = this.afs.collection('files').valueChanges();
  }

  importImages(event) {
    this.uploads = [];
    const filelist = event.target.files;
    const allPercentage: Observable<number>[] = [];

    for (const file of filelist) {
      const path = `files/${file.name}`;
      const ref = this.storage.ref(path);
      const task = this.storage.upload(path, file);
      const _percentage$ = task.percentageChanges();
      allPercentage.push(_percentage$);

      const uploadTrack = {
        fileName: file.name,
        percentage: _percentage$
      }
      this.uploads.push(uploadTrack);

      task.then((f) => {
        return f.ref.getDownloadURL().then((url) => {
          return this.afs.collection('files').add({
            name: f.metadata.name,
            url: url
          });
        });
      });
    }

    this.allPercentage = combineLatest(allPercentage).pipe(
      map((percentages) => {
        let result = 0;
        for (const percentage of percentages) {
          result += percentage;
        }
        return result / percentages.length;
      }),
      tap(console.log)
    );
  }

  logout(): void {
    this.router.navigate(["login"]);
  }
}

Step-8. File Upload Template (file-upload.component.html)

<mat-toolbar color="primary">
  <mat-toolbar-row>
    <span>Image Uploading Cloud</span>
    <span class="example-fill-remaining-space"></span>
    <button mat-raised-button (click)="logout()" color="primary">Logout</button>
    <button mat-icon-button [matMenuTriggerFor]="menu">
      <mat-icon>more_vert</mat-icon>
    </button>
    <mat-menu #menu="matMenu">
      <button mat-menu-item>
        <mat-icon>dialpad</mat-icon>
        <span>Redial</span>
      </button>
      <button mat-menu-item disabled>
        <mat-icon>voicemail</mat-icon>
        <span>Check voicemail</span>
      </button>
      <button mat-menu-item>
        <mat-icon>notifications_off</mat-icon>
        <span>Disable alerts</span>
      </button>
    </mat-menu>
  </mat-toolbar-row>
</mat-toolbar>

<h2>UPLOADING IMAGES CLOUD</h2>
<div *ngFor="let upload of uploads">
  <h3>Upload of {{upload.fileName}}</h3>
  <p> Progress: {{upload.percentage | async}}</p>
</div>

<h2>{{allPercentage | async}}</h2>

<input type="file" multiple (change)="importImages($event)">

<h2>FIRESTORE VALUES</h2>
<div *ngFor="let file of files | async">
  <h3>Upload of {{file.name}} DONE and saved in firestore</h3>
  <p>url: {{file.url}} <img [src]="file.url" height="40" /></p>
</div>

Leave a Comment

Your email address will not be published. Required fields are marked *