In this tutorial, I will show you way to build an Angular Material 14 File upload to Rest API example using HttpClient, FormData and Progress Bar.
More Practice:
– Angular 14 File upload example with Bootstrap
– Angular 14 + Spring Boot: File upload example
– Angular 14 + Node Express: File Upload example
– Angular 14 CRUD Application with Rest API
– Angular 14 Form Validation example (Reactive Forms)
– Angular 14 JWT Authentication and Authorization example
Serverless with Firebase:
Angular 14 File Upload to Firebase Storage example
Newer versions:
– Angular Material 15 File upload example
– Angular Material 16 File upload example
Contents
- Overview
- Technology
- Rest API for File Upload & Storage
- Setup Angular Material 14 File Upload Project
- Angular Material 14 File Upload example
- Install Angular Material
- Set up App Module
- Create Angular Service for Upload Files
- Create Component for Upload Files
- Add Upload File Component to App Component
- Run the App
- Further Reading
- Conclusion
- Source Code
Overview
We’re gonna create an Angular Material 14 File upload to Rest API application in that user can:
- see the upload process (percentage)
- view all uploaded files
- download by clicking on the file name
And the upload progress is finished.
Technology
- Angular 14
- RxJS 7
- Angular Material 14
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
Or: Spring Boot Multipart File upload (to database) example
Setup Angular Material 14 File Upload Project
Let’s open cmd and use Angular CLI to create a new Angular 14 Project as following command:
ng new angular-material-14-file-upload
? 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/file-upload
Now you can see that our project directory structure looks like this.
Angular Material 14 File Upload example
Let me explain it briefly.
– We import necessary Angular Material library, components in app.module.ts.
– file-upload.service provides methods to save File and get Files from Rest API Server using HttpClient
.
– file-upload.component contains upload form, progress bar, display of list files.
– app.component is the container that we embed all components.
– index.html for importing the Font and Icons.
Install Angular Material
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), 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 { AppComponent } from './app.component';
import { FileUploadComponent } from './components/file-upload/file-upload.component';
import { NoopAnimationsModule } from '@angular/platform-browser/animations';
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 { MatListModule } from '@angular/material/list';
const materialModules = [
MatCardModule,
MatToolbarModule,
MatButtonModule,
MatInputModule,
MatFormFieldModule,
MatProgressBarModule,
MatListModule
];
@NgModule({
declarations: [
AppComponent,
FileUploadComponent
],
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 Spring Boot File Upload server.
Create Component for Upload Files
Let’s create a File Upload UI with Progress Bar, Card, Button and Message.
First we need to use the following imports:
file-upload.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 FileUploadComponent implements OnInit {
currentFile?: File;
progress = 0;
message = '';
fileName = 'Select File';
fileInfos?: Observable<any>;
constructor(private uploadService: FileUploadService) { }
}
Next we define selectFile()
method. It helps us to get the currentFile
as the first Item and fileName
from input event.
selectFile(event: any): void {
if (event.target.files && event.target.files[0]) {
const file: File = event.target.files[0];
this.currentFile = file;
this.fileName = this.currentFile.name;
} else {
this.fileName = 'Select File';
}
}
Next we write upload()
method for upload file:
export class FileUploadComponent implements OnInit {
currentFile?: File;
progress = 0;
message = '';
fileName = 'Select File';
fileInfos?: Observable<any>;
constructor(private uploadService: FileUploadService) { }
selectFile(event: any): void {
if (event.target.files && event.target.files[0]) {
const file: File = event.target.files[0];
this.currentFile = file;
this.fileName = this.currentFile.name;
} else {
this.fileName = 'Select File';
}
}
upload(): void {
this.progress = 0;
this.message = "";
if (this.currentFile) {
this.uploadService.upload(this.currentFile).subscribe(
(event: any) => {
if (event.type === HttpEventType.UploadProgress) {
this.progress = Math.round(100 * event.loaded / event.total);
} else if (event instanceof HttpResponse) {
this.message = event.body.message;
this.fileInfos = this.uploadService.getFiles();
}
},
(err: any) => {
console.log(err);
this.progress = 0;
if (err.error && err.error.message) {
this.message = err.error.message;
} else {
this.message = 'Could not upload the file!';
}
this.currentFile = undefined;
});
}
}
}
We call uploadService.upload()
method on the currentFile
if it exists.
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(): void {
this.fileInfos = this.uploadService.getFiles();
}
Now we create the HTML template of the Upload File UI. Add the following content to file-upload.component.html file:
<div>
<mat-toolbar *ngIf="currentFile" class="progress-bar">
<mat-progress-bar color="accent" [value]="progress"></mat-progress-bar>
<span class="progress">{{ progress }}%</span>
</mat-toolbar>
<mat-form-field>
<div>
<mat-toolbar>
<input matInput [value]="fileName" />
<button
mat-flat-button
color="primary"
[disabled]="!currentFile"
(click)="upload()"
>
Upload
</button>
</mat-toolbar>
<input
type="file"
id="fileInput"
(change)="selectFile($event)"
name="fileInput"
/>
</div>
</mat-form-field>
</div>
<div *ngIf="message" class="message">
{{ message }}
</div>
<mat-card class="example-card">
<mat-card-header>
<mat-card-title>List of Files</mat-card-title>
</mat-card-header>
<mat-card-content>
<mat-list role="list">
<mat-list-item role="listitem" *ngFor="let file of fileInfos | async">
<a href="{{ file.url }}">{{ file.name }}</a>
</mat-list-item>
</mat-list>
</mat-card-content>
</mat-card>
Don’t forget to customize the style with CSS in file-upload.component.css:
.progress-bar {
padding: 0;
}
.progress {
width: 50px;
}
#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%;
}
.message {
background-color: #ddd;
padding: 15px;
color: #333;
border: #aaa solid 1px;
border-radius: 4px;
margin-bottom: 10px;
}
Add Upload File Component to App Component
Open app.component.html and embed the FileUpload Component with <app-file-upload>
tag.
<div class="container">
<h3>bezkoder.com</h3>
<h4>{{ title }}</h4>
<app-file-upload></app-file-upload>
</div>
app.component.css
.container {
width: 600px;
margin: 20px auto;
}
.container h3{
font-size: xx-large;
}
.container h4{
font-size: x-large;
}
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 14 File Upload';
}
Run the App
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
Because we configure CORS for origin: http://localhost:8081
, so you need to run Angular 14 Client 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 14 + Spring Boot: File upload example
- Angular 14 + Node Express: File Upload example
- Angular 14 CRUD Application with Rest API
- Angular 14 Form Validation example (Reactive Forms)
- Angular 14 JWT Authentication and Authorization example
Conclusion
Today we’re learned how to build an example for File upload to Rest API with Progress Bar using Angular Material 14 and FormData. We also provide the ability to show list of files, upload progress and to download file from the server.
If you want to upload multiple images with preview like this:
You can find the instruction here:
Angular Material 14 Image upload with Preview example
Or Serverless with Firebase:
Angular 14 Upload File to Firebase Storage example
Happy Learning! See you again.
Source Code
The source code for the Angular Material 14 App is uploaded to Github.
Bootstrap instead: Angular 14 File upload example with Bootstrap