Angular 17 Multiple Files upload example

In this tutorial, I will show you way to build Angular 17 Multiple File upload example using with FormData and Bootstrap.

More Practice:
Angular 17 Multiple Files upload with Progress Bar example
Angular 17 Multiple Image Upload with Preview example
Angular 17 + Spring Boot: File upload example
Angular 17 + Node Express: File Upload example
Angular 17 CRUD example with Rest API
Angular 17 Login and Registration example with Web Api
– Using Material: Angular Material 17 Image upload with Preview example


Overview

We will create an Angular 17 Multiple File upload application in that user can:

  • see the notification message of each file upload status
  • view all uploaded files
  • download file by clicking on the file name

angular-17-multiple-file-upload-example

If one of the upload progress is not successful:

angular-17-multiple-file-upload-example-handle-error

If you want to upload Images with Preview, kindly visit:
Angular 17 Multiple Images Upload with Preview example

Technology

  • Angular 17
  • RxJS 7
  • Bootstrap 4

Rest API for File Upload & Storage

Here is the API that our Angular App will work with:

Methods Urls Actions
POST /upload upload a File
GET /files get List of Files (name & url)
GET /files/[filename] download a File

You can find how to implement the Rest APIs Server at one of following posts:
Node.js Express File Upload Rest API example
Node.js Express File Upload to MongoDB example
Node.js Express File Upload to Google Cloud Storage example
Spring Boot Multipart File upload (to static folder) example

Setup Angular 17 Project

Let’s open cmd and use Angular CLI to create a new Angular Project as following command:

ng new angular-17-multiple-file-upload
? Which stylesheet format would you like to use? CSS
? Do you want to enable Server-Side Rendering (SSR) and Static Site Generation (SSG/Prerendering)? No

We also need to generate some Components and Services:

ng g s services/file-upload
ng g c components/upload-files

Now you can see that our project directory structure looks like this.

Angular 17 multiple File upload project

angular-17-multiple-file-upload-example-project

Let me explain it briefly.

– We import necessary library in app.config.ts.
file-upload.service provides methods to save File and get Files from Rest API Server.
upload-files.component contains upload multiple files form, display of list files.
app.component is the container that we embed all components.
index.html or angular.json for importing the Bootstrap.

Set up HttpClient Module

Open app.config.ts and import provideHttpClient from Angular Http Module:

import { ApplicationConfig } from '@angular/core';
import { provideRouter } from '@angular/router';
import { provideHttpClient } from '@angular/common/http';

import { routes } from './app.routes';

export const appConfig: ApplicationConfig = {
  providers: [
    provideRouter(routes),
    provideHttpClient()
  ]
};

Add Bootstrap to the project

Open index.html and add following line into <head> tag:

<!DOCTYPE html>
<html lang="en">
  <head>
    ...
    <link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/css/bootstrap.min.css" />
  </head>
  ...
</html>

Another way is installing Bootstrap module with command: npm install [email protected].
Then add following code into angular.json:

"styles": [
  "node_modules/bootstrap/dist/css/bootstrap.min.css",
  "src/styles.css"
],
"scripts": [
  "node_modules/jquery/dist/jquery.slim.min.js",
  "node_modules/popper.js/dist/umd/popper.min.js",
  "node_modules/bootstrap/dist/js/bootstrap.min.js"
]

Create Angular 17 Service for Upload Multiple Files

This service will use Angular HttpClient to send HTTP requests.
There are 2 functions:

  • upload(file): returns Observable<HttpEvent<any>> that we’re gonna use in Multiple File Upload Component
  • getFiles(): returns a list of Files’ information as Observable object

services/file-upload.service.ts

import { Injectable } from '@angular/core';
import { HttpClient, HttpRequest, HttpEvent } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class FileUploadService {
  private baseUrl = 'http://localhost:8080';

  constructor(private http: HttpClient) { }

  upload(file: File): Observable<HttpEvent<any>> {
    const formData: FormData = new FormData();

    formData.append('file', file);

    const req = new HttpRequest('POST', `${this.baseUrl}/upload`, formData, {
      responseType: 'json'
    });

    return this.http.request(req);
  }

  getFiles(): Observable<any> {
    return this.http.get(`${this.baseUrl}/files`);
  }
}

FormData is a data structure that can be used to store key-value pairs. We use it to build an object which corresponds to an HTML form with append() method.

– We call the request(PostRequest) & get() method of HttpClient to send an HTTP POST & Get request to the Multiple Files Upload Rest server.

Create Angular 17 Component for Multiple File Upload

Let’s create template UI for Upload Multiple Files component with Card, Button and Message.

First we need to use the following imports:

upload-files.component.ts

import { Component, OnInit } from '@angular/core';
import { CommonModule } from '@angular/common';
import { HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs';
import { FileUploadService } from '../../services/file-upload.service';

@Component({
  selector: 'app-upload-files',
  standalone: true,
  imports: [CommonModule],
  templateUrl: './upload-files.component.html',
  styleUrl: './upload-files.component.css'
})
export class UploadFilesComponent implements OnInit { ... }

Then we define the some variables and inject FileUploadService as follows:

export class UploadFilesComponent implements OnInit {
  selectedFiles?: FileList;
  message: string[] = [];

  fileInfos?: Observable<any>;

  constructor(private uploadService: FileUploadService) { }

}

Next we define selectFiles() method. It helps us to get the selected Files that we’re gonna upload.

selectFiles(event): void {
  this.message = [];
  this.selectedFiles = event.target.files;
}

Now we iterate over the selected Files above and call upload() method on each file item.

uploadFiles(): void {
  this.message = [];

  if (this.selectedFiles) {
    for (let i = 0; i < this.selectedFiles.length; i++) {
      this.upload(this.selectedFiles[i]);
    }
  }
}

Next we define upload() method for uploading each file:

upload(file: File): void {
  if (file) {
    this.uploadService.upload(file).subscribe({
      next: (event: any) => {
        if (event instanceof HttpResponse) {
          const msg = file.name + ": Successful!";
          this.message.push(msg);
          this.fileInfos = this.uploadService.getFiles();
        }
      },
      error: (err: any) => {
        let msg = file.name + ": Failed!";

        if (err.error && err.error.message) {
          msg += " " + err.error.message;
        }

        this.message.push(msg);
        this.fileInfos = this.uploadService.getFiles();
      }
    });
  }
}

We call uploadService.upload() method on each file.

If the transmission is done, the event will be a HttpResponse object. At this time, we call uploadService.getFiles() to get the files’ information and assign the result to fileInfos variable.

We also need to do this work in ngOnInit() method:

ngOnInit(): void {
  this.fileInfos = this.uploadService.getFiles();
}

Now we create the HTML template of the Upload multiple Files UI.
Add the following content to upload-files.component.html file:

<div class="row">
  <div class="col-8">
    <label class="btn btn-default p-0">
      <input type="file" multiple (change)="selectFiles($event)" />
    </label>
  </div>

  <div class="col-4">
    <button
      class="btn btn-success btn-sm"
      [disabled]="!selectedFiles"
      (click)="uploadFiles()"
    >
      Upload
    </button>
  </div>
</div>

@if (message.length) {
<div class="alert alert-secondary my-3" role="alert">
  <ul>
    @for (msg of message; track i; let i = $index) {
    <li>{{ msg }}</li>
    }
  </ul>
</div>
}

<div class="card mt-3">
  <div class="card-header">List of Files</div>
  <ul class="list-group list-group-flush">
    @for (file of fileInfos | async; track file.name) {
    <li class="list-group-item">
      <a href="{{ file.url }}">{{ file.name }}</a>
    </li>
    }
  </ul>
</div>

Add Upload Multiple Files Component to App Component

Import UploadFilesComponent in app.component.ts

import { Component } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterOutlet } from '@angular/router';
import { UploadFilesComponent } from './components/upload-files/upload-files.component';

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [CommonModule, RouterOutlet, UploadFilesComponent],
  templateUrl: './app.component.html',
  styleUrl: './app.component.css'
})
export class AppComponent {
  title = 'Angular 17 Multiple Files Upload example';
}

Open app.component.html and embed the Upload Files Component with <app-upload-files> tag.

<div class="container" style="width:500px">
  <div class="my-3">
    <h3>bezkoder.com</h3>
    <h4>{{ title }}</h4>
  </div>

  <app-upload-files></app-upload-files>
</div>

Run the App

If you use one of following server:
Node.js Express File Upload Rest API example
Node.js Express File Upload to MongoDB example
Node.js Express File Upload to Google Cloud Storage example
Spring Boot Multipart File upload (to static folder) example

You need run with port 8081 for CORS origin http://localhost:8081 with command:
ng serve --port 8081

Open Browser with url http://localhost:8081/ and check the result.

Further Reading

Conclusion

Today we’re learned how to build an Angular 17 example for multiple Files upload to Rest API using and FormData. We also provide the ability to show list of files using Bootstrap.

You can find how to implement the Rest APIs Server at one of following posts:
Node.js Express File Upload Rest API example
Node.js Express File Upload to MongoDB example
Node.js Express File Upload to Google Cloud Storage example
Spring Boot Multipart File upload (to static folder) example

Source Code

The source code for this Angular 17 Client is uploaded to Github.

More Practice: Angular 17 Multiple Files upload with Progress Bar example

If you want to upload Images with Preview, kindly visit:
Angular 17 Multiple Images Upload with Preview example