In this tutorial, I will show you way to build (Multiple) Image upload and Preview example with Web API/Rest API using Angular Material 16, FormData and Progress Bar.
More Practice:
– Angular 16 + Bootstrap: Multiple Images Upload with Preview
– Angular 16 + Spring Boot: File upload example
– Angular 16 + Node Express: File Upload example
– Angular 16 CRUD Application with Rest API
– Angular 16 Form Validation example
– Angular 16 JWT Authentication and Authorization example
Serverless with Firebase:
Angular 16 Upload File to Firebase Storage example
Contents
- Overview
- Technology
- Rest API for Image Upload & Storage
- Setup Angular Material 16 Image Upload Preview Project
- Angular Material 16 project for Image upload
- Install Angular Material 16
- Set up App Module
- Create Angular Service for Upload Files
- Create Angular Material 16 Component for Upload Images
- Add Upload Multiple Images Component to App Component
- Run the App
- Further Reading
- Conclusion
Overview
We will create an Angular Material 16 (Multiple) Image upload with Preview application in that user can:
- see the preview of images that will be uploaded
- see the upload process (percentage) of all uploading images
- view all uploaded images
- download image by clicking on the file name
Here are screenshots of our React App:
– Before upload:
– When Upload is done:
– List of Images Display with download Urls:
– Handle error and show status for each image upload:
Technology
- Angular 16
- RxJS 7
- Angular Material 16
Rest API for Image Upload & Storage
Here are Rest APIs that we will use Axios to make HTTP requests:
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 example
Setup Angular Material 16 Image Upload Preview Project
Let’s open cmd and use Angular CLI to create a new Angular Project as following command:
ng new angular-material-16-image-upload-preview
? 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/file-upload
ng g c components/upload-images
Now you can see that our project directory structure looks like this.
Angular Material 16 project for Image upload
Let me explain it briefly.
– We import necessary library, components in app.module.ts.
– file-upload.service provides methods to save File and get Files from Rest Apis Server.
– upload-images.component contains upload multiple images form, preview, some progress bars, display list of images.
– app.component is the container that we embed all components.
– index.html for importing the Font and Icons.
Install Angular Material 16
Set up your Angular Material project by running the command:
ng add @angular/material
You need to answer some questions:
ℹ Using package manager: npm
✔ Found compatible package version: @angular/[email protected].
✔ Package information loaded.
The package @angular/[email protected] will be installed and executed.
Would you like to proceed? Yes
✔ Package successfully installed.
? Choose a prebuilt theme name, or "custom" for a custom theme:
Indigo/Pink [ Preview: https://material.angular.io?theme=indigo-pink ]
> Deep Purple/Amber [ Preview: https://material.angular.io?theme=deeppurple-amber ]
Pink/Blue Grey [ Preview: https://material.angular.io?theme=pink-bluegrey ]
Purple/Green [ Preview: https://material.angular.io?theme=purple-green ]
Custom
? Set up global Angular Material typography styles? Yes
? Include the Angular animations module? Do not include
The command will install Angular Material, the Component Dev Kit (CDK), (with/without) Angular Animations and additionally perform the following configurations:
- Add project dependencies to package.json
- Add the Roboto font to index.html
- Add the Material Design icon font to index.html
- Add a few global CSS styles to styles.css
Set up App Module
Open app.module.ts, import HttpClientModule
and several Angular Material modules:
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpClientModule } from '@angular/common/http';
import { NoopAnimationsModule } from '@angular/platform-browser/animations';
import { AppComponent } from './app.component';
import { UploadImagesComponent } from './components/upload-images/upload-images.component';
import { MatCardModule } from '@angular/material/card';
import { MatToolbarModule } from '@angular/material/toolbar';
import { MatButtonModule } from '@angular/material/button';
import { MatInputModule } from '@angular/material/input';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatProgressBarModule } from '@angular/material/progress-bar';
import { MatGridListModule } from '@angular/material/grid-list';
const materialModules = [
MatCardModule,
MatToolbarModule,
MatButtonModule,
MatInputModule,
MatFormFieldModule,
MatProgressBarModule,
MatGridListModule,
];
@NgModule({
declarations: [AppComponent, UploadImagesComponent],
imports: [
BrowserModule,
HttpClientModule,
NoopAnimationsModule,
...materialModules,
],
providers: [],
bootstrap: [AppComponent],
})
export class AppModule {}
Create Angular Service for Upload 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/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, {
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 Material 16 Component for Upload Images
Let’s create a Multiple Images Upload UI with Preview, 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 { HttpEventType, HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs';
import { FileUploadService } from 'src/app/services/file-upload.service';
Then we define the some variables and inject FileUploadService
as follows:
export class UploadImagesComponent implements OnInit {
selectedFiles?: FileList;
selectedFileNames: string[] = [];
progressInfos: any[] = [];
message: string[] = [];
previews: string[] = [];
imageInfos?: Observable<any>;
constructor(private uploadService: FileUploadService) { }
}
The progressInfos
is an array that contains items for display upload progress of each images. Each item will have 2 fields: percentage & fileName.
selectedFileNames
array will be used for displaying selected files.
Next we define selectFiles()
method. It helps us to get the selected Images that we’re gonna upload.
selectFiles(event: any): void {
this.message = [];
this.progressInfos = [];
this.selectedFileNames = [];
this.selectedFiles = event.target.files;
this.previews = [];
if (this.selectedFiles && this.selectedFiles[0]) {
const numberOfFiles = this.selectedFiles.length;
for (let i = 0; i < numberOfFiles; i++) {
const reader = new FileReader();
reader.onload = (e: any) => {
console.log(e.target.result);
this.previews.push(e.target.result);
};
reader.readAsDataURL(this.selectedFiles[i]);
this.selectedFileNames.push(this.selectedFiles[i].name);
}
}
}
We use FileReader
with readAsDataURL()
method to get the image preview URL and put it into previews
array. This method produces data as a data: URL representing the file’s data as a base64 encoded string. The URL life is tied to the document in the window on which it was created.
Also use selectedFiles
array for accessing current selected 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(i, this.selectedFiles[i]);
}
}
}
Next we define upload()
method for uploading each image:
upload(idx: number, file: File): void {
this.progressInfos[idx] = { value: 0, fileName: file.name };
if (file) {
this.uploadService.upload(file).subscribe(
(event: any) => {
if (event.type === HttpEventType.UploadProgress) {
this.progressInfos[idx].value = Math.round(
(100 * event.loaded) / event.total
);
} else if (event instanceof HttpResponse) {
const msg = file.name + ": Successful!";
this.message.push(msg);
this.imageInfos = this.uploadService.getFiles();
}
},
(err: any) => {
this.progressInfos[idx].value = 0;
let msg = file.name + ": Failed!";
if (err.error && err.error.message) {
msg += " " + err.error.message;
}
this.message.push(msg);
}
);
}
}
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 imageInfos
variable.
We also need to do this work in ngOnInit()
method:
ngOnInit(): void {
this.imageInfos = this.uploadService.getFiles();
}
Now we create the HTML template of the Upload Images UI with Angular Material Components.
Add the following content to upload-images.component.html file:
<div *ngFor="let progressInfo of progressInfos">
<span>{{ progressInfo.fileName }}</span>
<mat-toolbar class="progress-bar">
<mat-progress-bar
color="accent"
[value]="progressInfo.value"
></mat-progress-bar>
<span class="progress">{{ progressInfo.value }}%</span>
</mat-toolbar>
</div>
<mat-form-field>
<div>
<mat-toolbar>
<input matInput [value]="selectedFileNames.length ? selectedFileNames.join(', ') : 'Select Images'" />
<button
mat-flat-button
color="primary"
[disabled]="!selectedFiles"
(click)="uploadFiles()"
>
Upload
</button>
</mat-toolbar>
<input
type="file"
id="fileInput"
name="fileInput"
accept="image/*" multiple
(change)="selectFiles($event)"
/>
</div>
</mat-form-field>
<div>
<img *ngFor='let preview of previews' [src]="preview" class="preview">
</div>
<div *ngIf="message.length" class="message">
<ul *ngFor="let msg of message; let i = index">
<li>{{ msg }}</li>
</ul>
</div>
<mat-card class="list-card">
<mat-card-header>
<mat-card-title>List of Images</mat-card-title>
</mat-card-header>
<mat-card-content>
<mat-grid-list cols="2" rowHeight="60px">
<div *ngFor="let image of imageInfos | async">
<mat-grid-tile><a href="{{ image.url }}" class="text-inside-grid">{{ image.name }}</a></mat-grid-tile>
<mat-grid-tile><img src="{{ image.url }}" alt="{{ image.name }}" class="image-inside-grid"/></mat-grid-tile>
</div>
</mat-grid-list>
</mat-card-content>
</mat-card>
Don’t forget to customize the style with CSS in upload-images.component.css:
.progress-bar {
padding: 0;
}
.progress {
width: 50px;
}
.mat-input-element {
font-size: medium;
font-weight: 200;
}
#fileInput {
position: absolute;
cursor: pointer;
z-index: 10;
opacity: 0;
height: 100%;
left: 0px;
top: 0px;
}
.mat-toolbar-single-row {
height: auto !important;
background: transparent;
padding: 0;
}
.mat-toolbar-single-row button {
width: 100px;
}
.mat-form-field {
width: 100%;
}
.mat-mdc-form-field {
display: block;
}
.message {
background-color: #ddd;
padding: 15px;
color: #333;
border: #aaa solid 1px;
border-radius: 4px;
margin: 15px 0;
}
.preview {
max-width: 200px;
vertical-align: middle;
}
.list-card {
margin-top: 20px;
}
.text-inside-grid {
position: absolute;
left: 5px;
}
.image-inside-grid {
height: 50px;
position: absolute;
right: 5px;
}
Add Upload Multiple Images Component to App Component
Open app.component.html and embed the Upload Images Component with <app-upload-images>
tag.
<div class="container">
<h3>bezkoder.com</h3>
<h4>{{ title }}</h4>
<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 Material 16 Image Upload with Preview';
}
app.component.css
.container {
width: 600px;
margin: 20px auto;
}
.container h3{
font-size: xx-large;
}
.container h4{
font-size: x-large;
}
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.
Or run on Stackblitz:
Further Reading
- Getting Started with Angular Material
- https://angular.io/api/common/http/HttpRequest
- Angular 16 + Spring Boot: File upload example
- Angular 16 + Node Express: File Upload example
- Angular 16 CRUD example with Rest API
- Angular 16 Form Validation example (Reactive Forms)
- Angular 16 JWT Authentication and Authorization example
Using Bootstrap: Angular 16 Multiple Images Upload with Preview example
Serverless: Angular 16 Upload File to Firebase Storage example
Conclusion
Today we’re learned how to build an example for (multiple) Image upload with preview using Angular Material 16. We also provide the ability to show list of images and display multiple progress bars.
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 16 Client is uploaded to Github.