Angular 8 upload Multiple Images with Web API example – BezKoder
In this tutorial, I will show you way to build Multiple Images upload example with Web API using Angular 8, Bootstrap and FormData with Progress Bars.
Newer versions:
– Angular 10 upload Multiple Images example
– Angular 11 Multiple Images Upload with Preview example
– Angular 12 Multiple Images Upload with Preview example
– Angular 14 Multiple Images Upload with Preview example
– Angular 15 Multiple Images Upload with Preview example
More Practice:
– Angular 8 + Node.js Express: File upload example
– Angular 8 + Spring Boot: File upload example
– Angular 8 JWT Authentication with HttpInterceptor and Router
– Angular 8 CRUD Application example with Web API
Overview
We will create an Angular multiple Images upload application in that user can:
- see the upload process (percentage) of all uploading images
- view all uploaded images
- download image by clicking on the file name
Technology
- Angular 8
- RxJS 6
- Bootstrap 4
Web 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 8 Project
Let’s open cmd and use Angular CLI to create a new Angular Project as following command:
ng new AngularUploadMultipleImages
? Would you like to add Angular routing? No
? Which stylesheet format would you like to use? CSS
We also need to generate some Components and Services:
ng g s services/upload-files
ng g c components/upload-images
Now you can see that our project directory structure looks like this.
Angular 8 App for multiple Images upload
Let me explain it briefly.
– We import necessary library, components in app.module.ts.
– upload-files.service provides methods to save File and get Files from Rest Apis Server.
– upload-images.component contains upload multiple images form, some progress bars, display list of images.
– app.component is the container that we embed all components.
– index.html for importing the Bootstrap.
Set up App Module
Open app.module.ts and import HttpClientModule
:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';
import { AppComponent } from './app.component';
import { UploadImagesComponent } from './components/upload-images/upload-images.component';
@NgModule({
declarations: [
AppComponent,
UploadImagesComponent
],
imports: [
BrowserModule,
HttpClientModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
Add Bootstrap to the project
Open index.html and add following line into <head>
tag:
<!DOCTYPE html>
<html lang="en">
<head>
...
<link type="text/css" rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" />
</head>
...
</html>
Create Angular Service for Upload Multiple Files
This service will use Angular HTTPClient
to send HTTP requests.
There are 2 functions:
upload(file)
: returnsObservable<HttpEvent<any>>
that we’re gonna use for tracking progressgetFiles()
: returns a list of Files’ information asObservable
object
services/upload-files.service.ts
import { Injectable } from '@angular/core';
import { HttpClient, HttpRequest, HttpEvent } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class UploadFilesService {
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, {
reportProgress: true,
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 set reportProgress: true
to exposes progress events. Notice that this progress event are expensive (change detection for each event), so you should only use when you want to monitor it.
– 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 Component for Upload Multiple Images
Let’s create a Multiple Images Upload UI with Progress Bars, Card, Button and Message.
First we need to use the following imports:
upload-images.component.ts
import { Component, OnInit } from '@angular/core';
import { UploadFilesService } from 'src/app/services/upload-files.service';
import { HttpEventType, HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs';
Then we define the some variables and inject UploadFilesService
as follows:
export class UploadFilesComponent implements OnInit {
selectedFiles: FileList;
progressInfos = [];
message = '';
fileInfos: Observable<any>;
constructor(private uploadService: UploadFilesService) { }
}
The progressInfos
is an array that contains items for display upload progress of each images. Each item will have 2 fields: percentage & fileName.
Next we define selectFiles()
method. It helps us to get the selected Images that we’re gonna upload.
selectFiles(event) {
this.progressInfos = [];
const files = event.target.files;
let isImage = true;
for (let i = 0; i < files.length; i++) {
if (files.item(i).type.match('image.*')) {
continue;
} else {
isImage = false;
alert('invalid format!');
break;
}
}
if (isImage) {
this.selectedFiles = event.target.files;
} else {
this.selectedFiles = undefined;
event.srcElement.percentage = null;
}
}
We check if each file has image type or not by using file.type.match('image.*')
. If one of the selected files is not an image file, the browser will alert 'invalid format!'
message.
Now we iterate over the selected Files above and call upload()
method on each file item.
uploadFiles() {
this.message = '';
for (let i = 0; i < this.selectedFiles.length; i++) {
this.upload(i, this.selectedFiles[i]);
}
}
Next we define upload()
method for uploading each image:
upload(idx, file) {
this.progressInfos[idx] = { value: 0, fileName: file.name };
this.uploadService.upload(file).subscribe(
event => {
if (event.type === HttpEventType.UploadProgress) {
this.progressInfos[idx].percentage = Math.round(100 * event.loaded / event.total);
} else if (event instanceof HttpResponse) {
this.fileInfos = this.uploadService.getFiles();
}
},
err => {
this.progressInfos[idx].percentage = 0;
this.message = 'Could not upload the file:' + file.name;
});
}
We use idx
for accessing index of the current File to work with progressInfos
array. Then we call uploadService.upload()
method on the file
.
The progress will be calculated basing on event.loaded
and event.total
.
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() {
this.fileInfos = this.uploadService.getFiles();
}
Now we create the HTML template of the Upload File UI.
Add the following content to upload-images.component.html file:
<div *ngFor="let progressInfo of progressInfos" class="mb-2">
<span>{{ progressInfo.fileName }}</span>
<div class="progress">
<div
class="progress-bar progress-bar-info progress-bar-striped"
role="progressbar"
attr.aria-valuenow="{{ progressInfo.percentage }}"
aria-valuemin="0"
aria-valuemax="100"
[ngStyle]="{ width: progressInfo.percentage + '%' }"
>
{{ progressInfo.percentage }}%
</div>
</div>
</div>
<label class="btn btn-default">
<input type="file" accept="image/*" multiple (change)="selectFiles($event)" />
</label>
<button
class="btn btn-success"
[disabled]="!selectedFiles"
(click)="uploadFiles()"
>
Upload
</button>
<div class="alert alert-light" role="alert">{{ message }}</div>
<div class="card">
<div class="card-header">List of Images</div>
<ul
class="list-group list-group-flush"
*ngFor="let file of fileInfos | async"
>
<li class="list-group-item">
<p><a href="{{ file.url }}">{{ file.name }}</a></p>
<img src="{{ file.url }}" alt="{{ file.name }}" height="80px">
</li>
</ul>
</div>
Add Upload Multiple Images Component to App Component
Open app.component.html and embed the UploadFile Component with <app-upload-images>
tag.
<div class="container" style="width: 600px;">
<div style="margin: 20px;">
<h3>bezkoder.com</h3>
<h4>{{ title }}</h4>
</div>
<app-upload-images></app-upload-images>
</div>
app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'Angular 8 Upload Multiple Images';
}
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
Newer versions:
– Angular 10 upload Multiple Images example
– Angular 11 Multiple Images Upload with Preview example
– Angular 12 Multiple Images Upload with Preview example
– Angular 14 Multiple Images Upload with Preview example
– Angular 15 Multiple Images Upload with Preview example
Conclusion
Today we’re learned how to build an example for multiple Images upload with Web API using Angular 8 and FormData. We also provide the ability to show list of images, multiple progress bars 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
The source code for the Angular 8 Client is uploaded to Github.