How To Add File Upload Progress Bar In Angular

Hello Friends, In this article, I will show you the way to add a file upload progress bar in angular. a progress bar is a graphical UI representation to visualize the progress of programmatic operation such as uploading, downloading, transfer, and installation of data. This article is to learn how to listen to the progress of the HTTP requests, especially when the data is being uploaded to the webserver.

Step: 1

we need to install an angular material kit using the following command.

ng add @angular/material

Step 2:

we need to import the HttpClientModule service in the app.module.ts file.

import { HttpClientModule } from '@angular/common/http';
import { NgModule } from '@angular/core';
import { MatProgressBarModule } from '@angular/material/progress-bar';
import { BrowserModule } from '@angular/platform-browser';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';


@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    BrowserAnimationsModule,
    AppRoutingModule,
    HttpClientModule,
    MatProgressBarModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Step 3:

open the src/app/app.component.ts file and add the following code inside of it.

import { HttpClient, HttpRequest, HttpResponse, HttpEventType } from '@angular/common/http';

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

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


export class AppComponent {
  title = 'FileUploadDemo';
  progress = 40
  constructor(private http: HttpClient) { }

  OnUpload(files: any) {

    if (files.length === 0) {
      return;
    }

    let fileUpload = <File>files[0];
    const filInput = new FormData();
    filInput.append('file', fileUpload, fileUpload.name);

    this.http.post(`https://localhost:44386/api/upload`, filInput, { reportProgress: true, observe: 'events' }).subscribe(
      event => {
        if (event.type === HttpEventType.UploadProgress) {
          let total: number = event.total ? event.total : 0;
          this.progress = Math.round(100 * event["loaded"] / total);
        } else if (event instanceof HttpResponse) {
          let res = event.body;
          console.log(res);
        }
      },
      error => {
        this.progress = 0;
        console.log(error);
      });
  }
}

Step 4:
Go to the src/app/app.component.html file and add the following code:

<input type="file" (change)="OnUpload($event)" />
<br />
<mat-progress-bar mode="determinate" [value]="progress"></mat-progress-bar>

Now run the application and see the output look likes below.

Submit a Comment

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

Subscribe

Select Categories