Angular 12 File Upload with Progress Bar using REST Apis Example

Angular 12 file/Image upload with progress bar example; This tutorial will guide you from scratch on how to upload files/images with progress bar in angular 12 app.

For building angular file upload wtih progress example tutorial will integrate Bootstrap UI in angular to create File upload UI component and animated progress bar.

Throughout this image/file upload progress bar in the angular 12 tutorial, you will learn how to upload files on the server and display upload progress using HttpEventType and FormData. And this tutorial also work with angular 8, angular 9, angular 10, angular 11 and angular 12 apps

File Upload with Progress Bar in Angular 12

  • Step 1 – Create New Angular App
  • Step 2 – Install and set up the Bootstrap 4 UI framework
  • Step 3 – Import Modules on app.module.ts
  • Step 4 – Create Upload File Components
  • Step 5 – Import Components app.component.ts
  • Step 6 – Create Services
  • Step 7 – Create Apis To Upload Image In Directory

Step 1 – Create New Angular App

First of all, open your terminal and execute the following command on it to install angular app:

ng new my-new-app

Step 2 – Install and set up the Bootstrap 4 UI framework

Open your terminal and execute the following command to install ng-file-upload Directive & toastr Notification in angular 12 app:

npm install bootstrap

Add the bootstrap style-sheet in the styles array in angular.json file.

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

Step 3 – Import Modules on app.module.ts

Then, Open app.module.ts file and import HttpClientModule, FormsModule, ReactiveFormsModule to app.module.ts file like following:

import { HttpClientModule } from '@angular/common/http';

@NgModule({
  declarations: [...],
  imports: [
     HttpClientModule
     ReactiveFormsModule
  ],
  bootstrap: [...]
})

export class AppModule { }

Step 4 – Create Upload File Components

In this step, create html markup for file upload form with input file element and image tag. So, visit src/app/app.component.html and update the following code into it:

<div class="container">
    <form [formGroup]="form" (ngSubmit)="submitUser()">

        <!-- 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 type="file" (change)="uploadFile($event)">
        </div>

        <div class="form-group input-group-lg">
            <input class="form-control" placeholder="Name" formControlName="name">
        </div>

        <div class="form-group">
            <button class="btn btn-danger btn-block btn-lg">Create</button>
        </div>
    </form>
</div>

Step 5 – Import Components app.component.ts

In this step, visit the src/app directory and open app.component.ts. Then add the following code into it:

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) {
    const file = (event.target as HTMLInputElement).files[0];
    this.form.patchValue({
      avatar: file
    });
    this.form.get('avatar').updateValueAndValidity()
  }

  submitUser() {
    this.fileUploadService.addUser(
      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:
          this.progress = Math.round(event.loaded / event.total * 100);
          console.log(`Uploaded! ${this.progress}%`);
          break;
        case HttpEventType.Response:
          console.log('User successfully created!', event.body);
          setTimeout(() => {
            this.progress = 0;
          }, 1500);

      }
    })
  }

}

Step 6 – Create Services

Execute the following command on create file upload service with HttpClient run the following command to create the service:

ng generate service file-upload

Then execute the following command on terminal to start the app to check out the File upload in the browser:

ng serve --open

Then, open the src/app/file-upload.service.ts file and add the following code
inside of it:

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) { }

  addUser(name: string, profileImage: File): Observable<any> {
    var formData: any = new FormData();
    formData.append("name", name);
    formData.append("avatar", profileImage);

    return this.http.post('http://localhost:3000/upload', 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(errorMessage);
    return throwError(errorMessage);
  }

}

Step 7 – Create Apis To Upload Image In Directory

You can make APIs for file/image upload by using the following tutorials. And you can use it with the angular app:

Conclusion

The Angular 12 File Upload with progress bar tutorial is over; throughout this tutorial, you have learned how to upload files on the server and display upload progress using HttpEventType and FormData.

Recommended Angular Tutorials

AuthorDevendra Dode

Greetings, I'm Devendra Dode, a full-stack developer, entrepreneur, and the proud owner of Tutsmake.com. My passion lies in crafting informative tutorials and offering valuable tips to assist fellow developers on their coding journey. Within my content, I cover a spectrum of technologies, including PHP, Python, JavaScript, jQuery, Laravel, Livewire, CodeIgniter, Node.js, Express.js, Vue.js, Angular.js, React.js, MySQL, MongoDB, REST APIs, Windows, XAMPP, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL, and Bootstrap. Whether you're starting out or looking for advanced examples, I provide step-by-step guides and practical demonstrations to make your learning experience seamless. Let's explore the diverse realms of coding together.

Leave a Reply

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