How To File Upload With Progress Bar Angular 15

Websolutionstuff | Jun-23-2023 | Categories : Angular

In this article, we will explore how to implement a file upload feature in Angular 15 with a progress bar. We will guide you through the step-by-step process of creating an Angular 15 application, importing the necessary modules, and writing the code to handle file uploads with a progress bar.

By the end of this tutorial, you will have a solid understanding of how to incorporate this feature into your Angular 15 projects.

Throughout this guide, we'll leverage the power of Angular 15 to create a seamless and visually appealing file upload experience for our users.

Whether you're building a file-sharing application, a content management system, or any other project that involves file uploads, this tutorial will equip you with the knowledge and skills to implement this feature effectively.

So, let's dive in and discover how we can leverage Angular 15 to enhance our applications with file uploads and progress bars.

By the end of this tutorial, you'll be able to create a user-friendly file upload feature that includes a progress bar, providing your users with a smooth and intuitive experience. Let's get started!

Step 1: Create a New Angular App

Start by creating a new Angular app using the following command.

ng new my-new-app


Step 2: Installing Bootstrap

This step guides you on how to install Bootstrap 4 in your Angular app using npm. Additionally, you need to add the Bootstrap CSS file to the angular.json file.

npm install bootstrap

Now you need to add bootstrap css in the angular.json file.


"styles": [



Step 3: Creating a Service

This step involves creating a service called FileUploadService to handle the file upload functionality. The service utilizes the HttpClient module to make HTTP requests to the server.

The fileUpload method sends a POST request with the file and progress tracking enabled. The errorMgmt method handles any errors that occur during the upload process.

ng generate service file-upload


import { Injectable } from '@angular/core';
import { Observable, throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';
import { HttpErrorResponse, HttpClient } from '@angular/common/http';
  providedIn: 'root'
export class FileUploadService {
  constructor(private http: HttpClient) { }
  fileUpload(name: string, profileImage: File): Observable {

    var formData: any = new FormData();
    formData.append("name", name);
    formData.append("image", profileImage);
    return'http://localhost:8000/upload.php', formData, {
      reportProgress: true,
      observe: 'events'
  errorMgmt(error: HttpErrorResponse) {
    let errorMessage = '';
    if (error.error instanceof ErrorEvent) {
      // Get client-side error
      errorMessage = error.error.message;
    } else {
      // Get server-side error
      errorMessage = `Error Code: ${error.status}\nMessage: ${error.message}`;
    return throwError(errorMessage);



Step 4: Importing Modules

In this step, you import the necessary modules (HttpClientModule and ReactiveFormsModule) and the FileUploadService into the AppModule.


import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { HttpClientModule } from '@angular/common/http';
import { ReactiveFormsModule } from '@angular/forms';
  declarations: [
  imports: [
  providers: [],
  bootstrap: [AppComponent]
export class AppModule { }

Step 5: Updating the View File

Here, you update the app.component.html file to include a form with file input and a progress bar.


<div class="row">
<div class="col-md-8">
<div class="container mt-5">
	<div class="card">
		<div class="card-header">
			<strong>How To File Upload With Progress Bar Angular 15 - Websolutionstuff</strong>
		<div class="card-body">
			<form [formGroup]="form" (ngSubmit)="submitFile()">
				<!-- Progress Bar -->
				<div class="progress form-group mb-2" *ngIf="progress > 0">
					<div class="progress-bar progress-bar-striped bg-success" role="progressbar" [style.width.%]="progress">{{progress}}%

				<div class="form-group">
					<input formControlName="file" type="file" class="form-control" (change)="uploadFile($event)">
				<div class="form-group">
					<button class="btn btn-success btn-block mt-2">Submit</button>


Step 6: Using the Component TypeScript File

In the app.component.ts file, you define the form, progress variable, and necessary methods. The uploadFile method updates the form with the selected file.

The submitFile method calls the fileUpload method from the service and subscribes to the progress events. Depending on the event type, progress updates and completion messages are logged.


import { Component } from '@angular/core';
import { FormBuilder, FormGroup } from "@angular/forms";
import { FileUploadService } from "./file-upload.service";
import { HttpEvent, HttpEventType } from '@angular/common/http';
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
export class AppComponent {
  form: FormGroup;
  progress: number = 0;
    public fb: FormBuilder,
    public fileUploadService: FileUploadService
  ) {
    this.form ={
      name: [''],
      avatar: [null]
  ngOnInit() { }
  uploadFile(event:any) {
    const file = ?[0] : '';
      avatar: file
  submitFile() {
    ).subscribe((event: HttpEvent<any>) => {
      switch (event.type) {
        case HttpEventType.Sent:
          console.log('Request has been made!');
        case HttpEventType.ResponseHeader:
          console.log('Response header has been received!');
        case HttpEventType.UploadProgress:
          var eventTotal = ? : 0;
          this.progress = Math.round(event.loaded / eventTotal * 100);
          console.log(`Uploaded! ${this.progress}%`);
        case HttpEventType.Response:
          console.log('File Upload Successfully!', event.body);
          setTimeout(() => {
            this.progress = 0;
          }, 2000);


Step 7: Creating a PHP API

In this step, we will create a PHP file called upload.php that takes care of the server-side logic for uploading files. This file will be responsible for receiving the file from the client and moving it to the desired location on the server.

Additionally, it will provide a JSON response back to the client, indicating whether the upload was successful or not.

Now that we have successfully implemented the file upload functionality, including the preview feature, in our Angular application, it's time to create an API file using PHP.

This API file, upload.php, will handle the actual process of receiving the uploaded files and storing it in a specific folder called "upload".

By creating the upload.php file, we will have a centralized component that handles the communication between the client-side Angular application and the server-side storage.

This ensures a smooth and efficient process for uploading and storing file in our application


    header("Access-Control-Allow-Origin: *");
    header("Access-Control-Allow-Methods: PUT, GET, POST");
    header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");
    $target_dir = "upload/";
    $target_file = $target_dir . basename($_FILES["image"]["name"]);
    $uploadOk = 1;
    $imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
    if (move_uploaded_file($_FILES["image"]["tmp_name"], $target_file)) {
        $t = "The file ". htmlspecialchars( basename( $_FILES["fileToUpload"]["name"])). " has been uploaded.";
    } else {
        $t = "Sorry, there was an error uploading your file.";
    header('Content-Type: application/json; charset=utf-8');
    echo json_encode([$t]);


 Step 8: Test the File Upload with Progress Bar

Start the Angular development server using the ng serve command and open the app in your browser. Try selecting a file using the file input field. The selected file should be displayed in the preview area.

ng serve

To run the PHP file on a different port, you can use a PHP development server. Open your terminal or command prompt, navigate to the directory where the upload.php file is located, and run the following command.

php -S localhost:8000



Step 9: Conclusion

In this tutorial, we learned how to implement file upload with a progress bar in Angular 15. We covered the step-by-step process of creating an Angular app, importing the required modules, and implementing the necessary logic in the component.

We also explored how to display a progress bar to track the upload progress and handle the API response. With this knowledge, you can now enhance your Angular applications by enabling users to upload files with a visually appealing progress bar.


You might also like:

Recommended Post
Featured Post
How To Restrict Special Characters Using jQuery Regex
How To Restrict Special Charac...

In this article, we will see how to restrict special characters using jquery regex. Here, we will learn how to crea...

Read More


How To Install Vue 3 In Laravel 9 With Vite
How To Install Vue 3 In Larave...

In this article, we will see how to install Vue 3 in laravel 9 with vite. In the previous article, we will install...

Read More


How To Generate PDF File In Laravel 10
How To Generate PDF File In La...

In this article, we will see how to generate a pdf file in laravel 10. Here, we will learn about laravel 10 ge...

Read More


PHP Array Functions With Example
PHP Array Functions With Examp...

In this tutorial we will learn php array functions with example. An array is a data structure that contains a group of e...

Read More