Angular 12 Firebase – Upload Image & Display List Images from Storage

In previous post, we have known how to upload file to Firebase Storage. This tutorial shows you way to get List Images and display in a simple Angular 12 App.

Updated Post:
Angular 5 Firebase – Upload/Display/Delete Images from Storage

Related Posts:
How to integrate Firebase with Angular 12
Angular 12 Firebase – Upload File to Storage
Angular 12 Firebase – Delete File from Storage

I. Technology

– Angular 12
– AngularFire2 4.0

II. How to do

1. Set up the Firebase Project & integrate Firebase with Angular 12 App

Please visit this post to know step by step.

2. Upload File Service

We get List Files from Firebase Storage by files’info (name/url) stored in Firebase Realtime Database.


import {AngularFireDatabase, FirebaseListObservable} from 'angularfire2/database';

@Injectable()
export class UploadFileService {

  private basePath = '/uploads';
  fileUploads: FirebaseListObservable;

  constructor(private db: AngularFireDatabase) {}
  // ...
  getFileUploads(query = {}) {
    this.fileUploads = this.db.list(this.basePath, {
      query: query
    });
    return this.fileUploads
  }
}

To know how to save file info to Firebase Realtime Database, please visit previous post:
Angular 12 Firebase – Upload File to Storage

3. Get and display List of Images


import {FirebaseListObservable} from 'angularfire2/database';
import {FileUpload} from '../fileupload';
import {UploadFileService} from '../upload-file.service';

export class ListUploadComponent implements OnInit {

  fileUploads: FirebaseListObservable;

  ngOnInit() {
    this.fileUploads = this.uploadService.getFileUploads({limitToLast: 6})
  }
}

HTML template:

<div *ngFor="let file of fileUploads | async">
	{{file.name}}
	<img src="{{file.url}}"/>
</div>

4. Check image format


if (file.type.match('image.*')) {
  // do something
} else {
  alert('invalid format!');
}

III. Practice

1. Project Overview

1.1 Goal

We will build an Angular 12 Firebase App that can:
– helps user choose image file from local and upload it to Firebase Storage
– show progress with percentage
– save image metadata to Firebase Realtime Database
(Functions above from the posts: Angular 12 Firebase – Upload File to Storage)
– get list Images and display

angular-4-firebase-storage-display-list-images-overview

1.2 Structure

angular-4-firebase-storage-get-list-files-structure

2. Step by step

2.1 Set up the Firebase Project & integrate Firebase with Angular 12 App

Please visit this post to know step by step.

angular-4-firebase-integration-copy-firebase-project-config

2.2 Add Firebase config to environments variable

Open /src/environments/environment.ts, add your Firebase configuration that we have saved when Popup window was shown:


export const environment = {
  production: false,
  firebase: {
    apiKey: 'xxx',
    authDomain: 'javasampleapproach-angular4.firebaseapp.com',
    databaseURL: 'https://javasampleapproach-angular4.firebaseio.com',
    projectId: 'javasampleapproach-angular4',
    storageBucket: 'javasampleapproach-angular4.appspot.com',
    messagingSenderId: 'xxx'
  }
};

2.3 Setup @NgModule


import {BrowserModule} from '@angular/platform-browser';
import {NgModule} from '@angular/core';

import {AngularFireDatabaseModule} from 'angularfire2/database';
import {AngularFireModule} from 'angularfire2';

import {AppComponent} from './app.component';
import {FormUploadComponent} from './upload/form-upload/form-upload.component';
import {UploadFileService} from './upload/upload-file.service';

import {environment} from '../environments/environment';

@NgModule({
  declarations: [
    AppComponent,
    FormUploadComponent
  ],
  imports: [
    BrowserModule,
    AngularFireModule.initializeApp(environment.firebase),
    AngularFireDatabaseModule
  ],
  providers: [UploadFileService],
  bootstrap: [AppComponent]
})
export class AppModule {}

2.4 Model Class


export class FileUpload {

  $key: string;
  name: string;
  url: string;
  file: File;

  constructor(file: File) {
    this.file = file;
  }
}

2.5 Service


import {Injectable} from '@angular/core';
import {AngularFireDatabase, FirebaseListObservable} from 'angularfire2/database';
import * as firebase from 'firebase';

import {FileUpload} from './fileupload';

@Injectable()
export class UploadFileService {

  private basePath = '/uploads';
  fileUploads: FirebaseListObservable;

  constructor(private db: AngularFireDatabase) {}

  pushFileToStorage(fileUpload: FileUpload, progress: {percentage: number}) {
    const storageRef = firebase.storage().ref();
    const uploadTask = storageRef.child(`${this.basePath}/${fileUpload.file.name}`).put(fileUpload.file);

    uploadTask.on(firebase.storage.TaskEvent.STATE_CHANGED,
      (snapshot) => {
        // in progress
        const snap = snapshot as firebase.storage.UploadTaskSnapshot
        progress.percentage = Math.round((snap.bytesTransferred / snap.totalBytes) * 100)
      },
      (error) => {
        // fail
        console.log(error)
      },
      () => {
        // success
        fileUpload.url = uploadTask.snapshot.downloadURL
        fileUpload.name = fileUpload.file.name
        this.saveFileData(fileUpload)
      }
    );
  }

  private saveFileData(fileUpload: FileUpload) {
    this.db.list(`${this.basePath}/`).push(fileUpload)
  }

  getFileUploads(query = {}) {
    this.fileUploads = this.db.list(this.basePath, {
      query: query
    });
    return this.fileUploads
  }

  deleteFileUpload(fileUpload: FileUpload) {
    this.deleteFileDatabase(fileUpload.$key)
      .then(() => {
        this.deleteFileStorage(fileUpload.name)
      })
      .catch(error => console.log(error))
  }

  private deleteFileDatabase(key: string) {
    return this.db.list(`${this.basePath}/`).remove(key)
  }

  private deleteFileStorage(name: string) {
    const storageRef = firebase.storage().ref()
    storageRef.child(`${this.basePath}/${name}`).delete()
  }
}

2.6 Form Upload Compoment


import {Component, OnInit} from '@angular/core';

import {UploadFileService} from '../upload-file.service';
import {FileUpload} from '../fileupload';

@Component({
  selector: 'form-upload',
  templateUrl: './form-upload.component.html',
  styleUrls: ['./form-upload.component.css']
})
export class FormUploadComponent implements OnInit {

  selectedFiles: FileList
  currentFileUpload: FileUpload
  progress: {percentage: number} = {percentage: 0}

  constructor(private uploadService: UploadFileService) {}

  ngOnInit() {
  }

  selectFile(event) {
    const file = event.target.files.item(0)

    if (file.type.match('image.*')) {
      this.selectedFiles = event.target.files;
    } else {
      alert('invalid format!');
    }
  }

  upload() {
    const file = this.selectedFiles.item(0)
    this.selectedFiles = undefined

    this.currentFileUpload = new FileUpload(file);
    this.uploadService.pushFileToStorage(this.currentFileUpload, this.progress)
  }
}

form-upload.component.html:

<div *ngIf="currentFileUpload" class="progress" style="width:400px">
	<div class="progress-bar progress-bar-info progress-bar-striped"
		role="progressbar" attr.aria-valuenow="{{progress.percentage}}"
		aria-valuemin="0" aria-valuemax="100"
		[ngStyle]="{width:progress.percentage+'%'}">
		{{progress.percentage}}%</div>
</div>

<label class="btn btn-default"> <input type="file"
	(change)="selectFile($event)">
</label>

<button class="btn btn-success" [disabled]="!selectedFiles"
	(click)="upload()">Upload</button>

2.7 DetailsUpload Component

details-upload.component.ts


import {Component, OnInit, Input} from '@angular/core';
import {FileUpload} from '../fileupload';
import {UploadFileService} from '../upload-file.service';

@Component({
  selector: 'details-upload',
  templateUrl: './details-upload.component.html',
  styleUrls: ['./details-upload.component.css']
})
export class DetailsUploadComponent implements OnInit {

  @Input() fileUpload: FileUpload;

  constructor(private uploadService: UploadFileService) {}

  ngOnInit() {
  }

  deleteFileUpload(fileUpload) {
    this.uploadService.deleteFileUpload(fileUpload)
  }
}

details-upload.component.html

{{fileUpload.name}}
<button (click)='deleteFileUpload(fileUpload)'
	class="btn btn-danger btn-xs" style="float: right">Delete</button>
<img src="{{fileUpload.url}}" alt="{{fileUpload.name}}" style="max-width:350px"/>

2.8 ListUpload Component

list-upload.component.ts


import {Component, OnInit} from '@angular/core';

import {FirebaseListObservable} from 'angularfire2/database';
import {FileUpload} from '../fileupload';
import {UploadFileService} from '../upload-file.service';

@Component({
  selector: 'list-upload',
  templateUrl: './list-upload.component.html',
  styleUrls: ['./list-upload.component.css']
})
export class ListUploadComponent implements OnInit {

  fileUploads: FirebaseListObservable;

  constructor(private uploadService: UploadFileService) {}

  ngOnInit() {
    this.fileUploads = this.uploadService.getFileUploads({limitToLast: 6})
  }

}

list-upload.component.html

<div class="panel panel-primary">
	<div class="panel-heading">List of Files</div>
	<div *ngFor="let file of fileUploads | async">
		<div class="panel-body">
			<details-upload [fileUpload]='file'></details-upload>
		</div>
	</div>
</div>

2.9 App Component

app.component.ts


import {Component} from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'JavaSampleApproach';
  description = 'Angular4-Firebase Demo';
}

app.component.html

<div class="container" style="width:400px">
	<div style="color: blue; margin-bottom: 20px">
		<h1>{{title}}</h1>
		<h3>{{description}}</h3>
	</div>

	<form-upload></form-upload>
	
	<br/>
	<br/>
	
	<list-upload></list-upload>
</div>

2.10 Check Result

Run the App, go to http://localhost:4200/.

angular-4-firebase-storage-display-list-images-overview

Check Firebase Console, the file that we deleted disappears:
– Database:
angular-4-firebase-storage-display-list-images-database-result

– Storage:
angular-4-firebase-storage-display-list-images-storage-result

IV. Source Code

Angular4FirebaseStorage-upload-display-list-images



By grokonez | September 21, 2017.

Last updated on March 26, 2021.



Related Posts


3 thoughts on “Angular 12 Firebase – Upload Image & Display List Images from Storage”

Got Something To Say:

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

*