How to Upload File in Angular

Rana Hasnain Khan Feb 02, 2024
  1. Importing Libraries in Angular
  2. Exporting Components and Declaring Variables in Angular
  3. Using basicUpload() to Upload Multiple Files in Angular
  4. Using basicUploadSingle() to Upload a Single File in Angular
  5. Using uploadAndProgress() to Upload Multiple Files in Angular
  6. Using UploadAndProgressSingle() to Upload a Single File in Angular
  7. Calling the Upload Function in Angular
  8. Summary
How to Upload File in Angular

We will introduce how to upload a file in four different styles using Angular.

We will also introduce how to display the progress bar when the file is uploading and display file upload completion messages when the upload is complete.

Importing Libraries in Angular

First, we will import libraries and set components for the file uploader.

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

@Component({
  selector: 'my-app',
  template: `
    Version = {{version.full}} <br/>
    <input type="file" (change)="upload($event.target.files)" />
    Upload Percent: {{percentDone}}% <br />
    
    <ng-container *ngIf="uploadSuccess">
      Upload Successful
    </ng-container> 
  `,
})

Exporting Components and Declaring Variables in Angular

Now, we will export our AppComponent and declare variables percentDone as number and UploadSuccess as a boolean. We will also declare a constructor which calls HttpClient.

# angular
export class AppComponent {
  percentDone: number;
  uploadSuccess: boolean;

  constructor(
    private http: HttpClient,
    ) { }
    
  version = VERSION

Using basicUpload() to Upload Multiple Files in Angular

There are four different styles of file upload in Angular, and the basicUpload() for multiple files is one of them. Multiple files can be uploaded at once in this style without displaying any progress bar for files.

basicUpload(files: File[]){
    var formData = new FormData();
    Array.from(files).forEach(f => formData.append('file', f))
    this.http.post('https://file.io', formData)
      .subscribe(event => {
        console.log('done')
      })
  }

We are sending upload requests to https://file.io, which can be changed with the backend server URL. The backend server will receive upload data of files, which will send a URL to the uploaded file.

Using basicUploadSingle() to Upload a Single File in Angular

The second style for uploading files in Angular is the basicUploadSingle() for a single file. In this style, the user can upload only one file at a time. This style will also not display progress while files are uploading.

basicUploadSingle(file: File){
    this.http.post('https://file.io', file)
      .subscribe(event => {
        console.log('done')
      })
  }

Using uploadAndProgress() to Upload Multiple Files in Angular

The third style for uploading files in Angular is uploadAndProgress() for multiple files. The user can upload multiple files simultaneously in this style, with a progress bar displaying the percentage of files uploaded.

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

Using UploadAndProgressSingle() to Upload a Single File in Angular

The fourth style for uploading files in Angular is uploadAndProgressSingle() for a single file. In this style, the user can simultaneously upload a single file, with a progress bar displaying the percentage of uploaded files.

uploadAndProgressSingle(file: File){
    this.http.post('https://file.io', file, {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;
        }
    });
  }

Calling the Upload Function in Angular

Now that we have added four styles of upload functions in angular, we can call our upload function with the desired style.

upload(files: File[]){
    //pick from one of the 4 styles of file uploads below
    this.uploadAndProgress(files);
  }

Output:

File Upload in Angular Image

Summary

We discussed four different styles of file upload in angular and how we can call them in our upload function. The full code is given below.

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

@Component({
  selector: 'my-app',
  template: `
    Version = {{version.full}} <br/>
    <input type="file" (change)="upload($event.target.files)" />
    Upload Percent: {{percentDone}}% <br />
    
    <ng-container *ngIf="uploadSuccess">
      Upload Successful
    </ng-container> 
  `,
})
export class AppComponent {
  percentDone: number;
  uploadSuccess: boolean;

  constructor(
    private http: HttpClient,
    ) { }
    
  version = VERSION
  
  upload(files: File[]){
    this.uploadAndProgress(files);
  }

  basicUpload(files: File[]){
    var formData = new FormData();
    Array.from(files).forEach(f => formData.append('file', f))
    this.http.post('https://file.io', formData)
      .subscribe(event => {
        console.log('done')
      })
  }

  basicUploadSingle(file: File){
    this.http.post('https://file.io', file)
      .subscribe(event => {
        console.log('done')
      })
  }
  
  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;
        }
    });
  }
  
  uploadAndProgressSingle(file: File){
    this.http.post('https://file.io', file, {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;
        }
    });
  }
}

Output:

File Upload In Angular

Rana Hasnain Khan avatar Rana Hasnain Khan avatar

Rana is a computer science graduate passionate about helping people to build and diagnose scalable web application problems and problems developers face across the full-stack.

LinkedIn