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.

angular.json

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

 

 

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

src/app/file-upload.service.ts

import { Injectable } from '@angular/core';
import { Observable, throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';
import { HttpErrorResponse, HttpClient } from '@angular/common/http';
  
@Injectable({
  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 this.http.post('http://localhost:8000/upload.php', formData, {
      reportProgress: true,
      observe: 'events'
    }).pipe(
      catchError(this.errorMgmt)
    )
  }
  
  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}`;
      console.log(error);
    }
    console.log(errorMessage);
    return throwError(errorMessage);
  }
}

 

 

Step 4: Importing Modules

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

src/app/app.module.ts

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';
  
@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    HttpClientModule,
    ReactiveFormsModule
  ],
  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.

src/app/app.component.html

<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>
		<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>
				</div>

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

 

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.

src/app/app.component.ts

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

upload.php

<?php
  
    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]);
    exit;
  
?>

 

 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 Upgrade PHP 8.0 to 8.1 in Ubuntu
How to Upgrade PHP 8.0 to 8.1...

Hey there! I recently needed to upgrade my PHP version from 8.0 to the latest 8.1 on my Ubuntu server. It's a smart...

Read More

Nov-03-2023

Laravel Datatables Example
Laravel Datatables Example

In this example, I will show you how to implement/install data tables in laravel. Datatables provides users with many fu...

Read More

May-16-2020

How To Validate International Phone Number Using jQuery
How To Validate International...

In this article, we will see how to validate international phone numbers using jquery. Here, we will learn about mo...

Read More

May-12-2023

MilesWeb Review: Why Go for Its Shared Hosting?
MilesWeb Review: Why Go for It...

For finding the right web hosting provider, you need to do a lot of research. There are hundreds of web hosting provider...

Read More

Nov-12-2021