Angular 13 File Upload with Progress Bar Tutorial

Complete Angular File Upload with progress bar guide, In this tutorial, you will find out how to create file uploading and display the progress of uploading files through a progress bar UI component dynamically.

For building angular file upload example, you will learn how to integrate Bootstrap UI in angular and how to use bootstrap to create File upload UI component and animated progress bar.

Not just that you will also ascertain the proper use of FormData API and HttpEventType to listen to the progress of file uploading.

The FormData interface provides a way to easily construct a set of key/value pairs representing form fields and their values, which can then be quickly sent using the XMLHttpRequest.send() method. It uses the same format a form would use if the encoding type were set to “multipart/form-data”.

The HttpEventType API is an ENUM type, which enumerates for the different kinds of HttpEvent.

This API comes handy when it comes to catching the sent request, track upload progress, handle the response header, manage the download progress of uploading files moreover you can create the custom event from an interceptor.

Angular 13 File Upload with Progress Bar Example

  • Install Angular Project
  • Configure Bootstrap
  • Create Upload File Components
  • Create File Uploading Service
  • Implement File Uploading
  • Run and Test Application

Install Angular Project

In this first step, you have to install the new angular application ignore this step if app already installed:

ng new angular-demo-app

Disable Strict Angular TypeStrict Errors

The latest version of Angular comes with strict mode, you have to manually disable the strict mode you can set “strict”: false, "noImplicitReturns": false and "strictTemplates": false inside the compilerOptions and angularCompilerOptions in tsconfig.json file.

Setting Up Bootstrap Package

After installing the project, move inside the project root. Further, you have to install the Bootstrap package:

npm i bootstrap

Move to angular.json file and register Bootstrap path as given below:

"styles": [
          "node_modules/bootstrap/dist/css/bootstrap.min.css",
          "src/styles.css"
         ]

Genrate Angular Components

Use angular command to generate component, and this component will be the locus of the file uploading feature.

ng generate component upload

Import and Register HttpClientModule

In this step, you have to import and register HttpClientModule from ‘@angular/common/http’ package in app.module.ts file:

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

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';

import { HttpClientModule } from '@angular/common/http';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    HttpClientModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})

export class AppModule { }

Download File Upload and Download REST API

In this step, you have to git clone the file Upload and download REST API project from GitHub in your angular project root:

Read more: Create Node Express & Multer File Upload & Download REST API

git clone https://github.com/remotestack377/node-file-upload-api.git

Next, get inside the node file upload rest api project:

cd node-file-upload-api

Further, install the required dependencies:

npm install

Build File Uploading Service

Next, you have to generate the angular service file, and this file will contain the methods and functions for handling file uploading and progress bar.

ng generate service upload

Open and update app/upload.service.ts file with following code:

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { HttpClient, HttpRequest, HttpEvent } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})

export class UploadService {

  private endpoint = 'http://localhost:8888';

  constructor(private httpClient: HttpClient) { }

  uploadFile(file: File): Observable<HttpEvent<any>> {
    const formData: FormData = new FormData();

    formData.append('file', file);

    const request = new HttpRequest('POST', `${this.endpoint}/upload-file`, formData, {
      reportProgress: true,
      responseType: 'json'
    });

    return this.httpClient.request(request);
  }

  getFiles(): Observable<any> {
    return this.httpClient.get(`${this.endpoint}/files`);
  }

}

Implement File Uploading

Open and update the below code in upload.component.ts file:

import { Component, OnInit } from '@angular/core';
import { UploadService } from '../upload.service';
import { Observable } from 'rxjs';
import { HttpEventType, HttpResponse } from '@angular/common/http';

@Component({
  selector: 'app-upload',
  templateUrl: './upload.component.html',
  styleUrls: ['./upload.component.css']
})

export class UploadComponent implements OnInit {

  chosenFiles: FileList;
  existingFile: File;
  progress = 0;
  msg = '';

  FileDetail: Observable<any>;

  constructor(private uploadService: UploadService) { }

  ngOnInit(): void {
    this.FileDetail = this.uploadService.getFiles();
  }

  chooseFile(event): void {
    this.chosenFiles = event.target.files;
  }

  upload(): void {
    this.progress = 0;
  
    this.existingFile = this.chosenFiles.item(0);

    this.uploadService.uploadFile(this.existingFile).subscribe( (event) => {
        if (event.type === HttpEventType.UploadProgress) {
          this.progress = Math.round(100 * event.loaded / event.total);
        } else if (event instanceof HttpResponse) {
          this.msg = event.body.message;
          this.FileDetail = this.uploadService.getFiles();
        }
      }, (error) => {
        this.progress = 0;
        this.msg = 'Error occured while uploading file';
        this.existingFile = undefined;
      });

    this.chosenFiles = undefined;
  }  

}

Open and update the below code in upload.component.html file:

<div class="progress" *ngIf="existingFile">
    <div
      class="progress-bar progress-bar-striped bg-danger"
      attr.aria-valuenow="{{ progress }}"
      aria-valuemin="0"
      aria-valuemax="100"
      [ngStyle]="{ width: progress + '%' }"
    >
      {{ progress }}%
    </div>
  </div>
  
  <label class="btn btn-default">
    <input type="file" (change)="chooseFile($event)" />
  </label>
  
  <button class="btn btn-primary" [disabled]="!chosenFiles" (click)="upload()">
    Upload
  </button>
  
  <div class="alert alert-light">{{ msg }}</div>
  
  <div class="card">
    <div class="card-header">Files Info</div>
    <ul
      class="list-group list-group-flush"
      *ngFor="let file of FileDetail | async"
    >
      <li class="list-group-item">
        <a href="{{ file.url }}">{{ file.name }}</a>
      </li>
    </ul>
  </div>

Open and update the below code in app.component.html file:

<h2 class="mb-4">Angular File Upload with Progress Bar Demo</h2>

<app-upload></app-upload>

Run and Test Application

Eventually, you need to start the angular and node rest api projects:

Open terminal window likewise execute the below command:

node index.js

Next, start the angular app, moreover start the browser append the below url on the address bar:

ng serve --open
http://localhost:4200

Angular File Upload with Progress Bar Tutorial

Conclusion

The Angular File Upload with progress bar tutorial is over; throughout this tutorial, you have learned how to upload files on the server and display upload progress using HttpEventType and FormData.

Download the full code of this comprehensive tutorial from GitHub.

Tutorial reference from: bezkoder.