Angular Image Upload with Progress Bar Example

By Hardik Savani November 5, 2023 Category : Angular

Hi,

This tutorial is focused on angular file upload progress bar percentage. This post will give you simple example of angular image upload with progress bar. let’s discuss about image upload progress bar angular. We will look at example of angular file upload with progress bar example. Let's get started with angular file upload with progress bar.

you can use this example with angular 6, angular 7, angular 8, angular 9, angular 10, angular 11, angular 12, angular 13, angular 14, angular 15, angular 16 and angular 17 version app.

In this example, i will create simple reactive form with image upload. we will create PHP api and use for image upload. in api service i will write code for showing progress bar percentage code.

I written step by step file uploading with progress bar in angular application, also created web services using php. so let's follow bellowing step and get preview like as bellow:

Preview:

Step 1: Create New App

You can easily create your angular app using bellow command:

ng new my-new-app

Step 2: Install Bootstrap

You have to run bellow command to install bootstrap 4 in angular.

npm install bootstrap

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

angular.json

....

"styles": [

"node_modules/bootstrap/dist/css/bootstrap.min.css",

"src/styles.css"

],

....

Step 3: Create Service

Here, we will create image upload service. so let's use bellow command and code for adding new image upload service.

ng generate service image-upload

src/app/image-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 ImageUploadService {

constructor(private http: HttpClient) { }

imageUpload(name: string, profileImage: File): Observable {

var formData: any = new FormData();

formData.append("name", name);

formData.append("image", profileImage);

return this.http.post('http://localhost:8001/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: Import Module

In this step, we need to import HttpClientModule, ReactiveFormsModule and ImageUploadService to app.module.ts file. so let's import it as like bellow:

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: Updated View File

Now here, we will updated our html file. we will create simple reactive form with input file element.

so let's put bellow code:

src/app/app.component.html

<div class="container" style="padding: 50px">

<h1>Image Upload with Progress Bar - ItSolutionStuff.com</h1>

<form [formGroup]="form" (ngSubmit)="submitImage()">

<!-- Progress Bar -->

<div class="progress form-group" *ngIf="progress > 0">

<div class="progress-bar progress-bar-striped bg-success" role="progressbar" [style.width.%]="progress">

</div>

</div>

<div class="form-group input-group-lg">

<input class="form-control" placeholder="Name" formControlName="name">

</div>

<div class="form-group">

<input type="file" (change)="uploadFile($event)">

</div>

<div class="form-group">

<button class="btn btn-success btn-block btn-lg">Submit</button>

</div>

</form>

</div>

Step 6: Use Component ts File

Let's use bellow code for component file.

so, let's update as like bellow:

src/app/app.component.ts

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

import { FormBuilder, FormGroup } from "@angular/forms";

import { ImageUploadService } from "./image-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 imageUploadService: ImageUploadService

) {

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()

}

submitImage() {

this.imageUploadService.imageUpload(

this.form.value.name,

this.form.value.avatar

).subscribe((event: HttpEvent) => {

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('Image Upload Successfully!', event.body);

setTimeout(() => {

this.progress = 0;

}, 1500);

}

})

}

}

Step 7: Create PHP API

Now we are ready to run our example, we will create api file using php. so you can create update.php file with "upload" folder and run with different port and call it. so let's create upload.php file as like bellow:

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 = "images/";

$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;

?>

Now we are ready to run both:

Run Angular App:

ng serve

Run PHP API:

php -S localhost:8001

Now you can run and check it.

I hope it can help you...

Tags :
Shares