Upload File With Progress Bar In Angular

Step 1: Create New Angular Application.

ng new upload-file-example

Step 2: Install bootstrap in project.

npm i bootstrap

Step 3: Add path in angular.json file

Step 4: Add code in app.component.ts file

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

@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.scss']
})
export class AppComponent {
    percentDone: number;
    uploadSuccess: boolean;

    constructor(private http: HttpClient) {
    }

    upload(files: File[]) {
        this.uploadAndProgress(files);
    }

    uploadAndProgress(files: File[]) {
        console.log(files)
        var formData = new FormData();
        Array.from(files).forEach(f => formData.append('file', f))

        this.http.post('https://file.io', formData, { reportProgress: true, observe: 'events' })
            .subscribe(event => {
                if (event.type === HttpEventType.UploadProgress) {
                    this.percentDone = Math.round(100 * event.loaded / event.total);
                } else if (event instanceof HttpResponse) {
                    this.uploadSuccess = true;
                }
            });
    }

}

Step 5: Add code in app.component.html file

<ng-container>
<div><input type="file" (change)="upload($event.target.files)" /></div>
<div class="progress">
    <div class="progress-bar mt-3" *ngIf="!uploadSuccess" style="width: 15%;" role="progressbar" aria-valuenow="25" aria-valuemin="0" aria-valuemax="100"> {{ percentDone }} %</div>
    <div *ngIf="uploadSuccess"style="width: 15%;     margin-top: 16px;
    " >Upload Successful</div>
</div>
</ng-container>

Output :

Submit a Comment

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

Subscribe

Select Categories