In this tutorial, I will show you way to build an Angular 10 File upload example using Bootstrap, FormData and Progress Bar.
Newer versions:
– Angular 11 File upload example
– Angular 12 File upload example
– Angular 13 File upload example
– Angular 14 File upload example
– Angular 15 File upload example
More Practice:
– Angular 10 + Spring Boot: File upload example
– Angular 10 JWT Authentication example with Web Api
– Angular 10 CRUD Application example with Web API
– Angular 10 Form Validation example (Reactive Forms)
Serverless with Firebase:
Angular 10 Firebase Storage: File Upload/Display/Delete example
Contents
- Technology
- Web API for File Upload & Storage
- Setup Angular 10 Project
- Angular 10 App for uploading File
- Set up App Module
- Add Bootstrap to the project
- 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
We’re gonna create an Angular 10 File upload application in that user can:
- see the upload process (percentage)
- view all uploaded files
- download by clicking on the file name
Technology
- Angular 10
- 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
Or: Spring Boot Multipart File upload (to database) example
Setup Angular 10 Project
Let’s open cmd and use Angular CLI to create a new Angular Project as following command:
ng new Angular10UploadFile
? 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/UploadFile
ng g c components/UploadFiles
Now you can see that our project directory structure looks like this.
Angular 10 App for uploading File
Let me explain it briefly.
– We import necessary library, components in app.module.ts.
– upload-file.service provides methods to save File and get Files from Spring Boot Server.
– upload-files.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 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 { UploadFilesComponent } from './components/upload-files/upload-files.component';
@NgModule({
declarations: [
AppComponent,
UploadFilesComponent
],
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 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-file.service.ts
import { Injectable } from '@angular/core';
import { HttpClient, HttpRequest, HttpEvent } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class UploadFileService {
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:
upload-files.component.ts
import { Component, OnInit } from '@angular/core';
import { UploadFileService } from 'src/app/services/upload-file.service';
import { HttpEventType, HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs';
Then we define the some variables and inject UploadFileService
as follows:
export class UploadFilesComponent implements OnInit {
selectedFiles: FileList;
currentFile: File;
progress = 0;
message = '';
fileInfos: Observable<any>;
constructor(private uploadService: UploadFileService) { }
}
Next we define selectFile()
method. It helps us to get the selected Files.
selectFile(event): void {
this.selectedFiles = event.target.files;
}
Next we define upload()
method for upload file:
upload(): void {
this.progress = 0;
this.currentFile = this.selectedFiles.item(0);
this.uploadService.upload(this.currentFile).subscribe(
event => {
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 => {
this.progress = 0;
this.message = 'Could not upload the file!';
this.currentFile = undefined;
});
this.selectedFiles = undefined;
}
We use selectedFiles
for accessing current File as the first Item. Then we call uploadService.upload()
method on the currentFile
.
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 upload-files.component.html file:
<div *ngIf="currentFile" class="progress">
<div
class="progress-bar progress-bar-info progress-bar-striped"
role="progressbar"
attr.aria-valuenow="{{ progress }}"
aria-valuemin="0"
aria-valuemax="100"
[ngStyle]="{ width: progress + '%' }"
>
{{ progress }}%
</div>
</div>
<label class="btn btn-default">
<input type="file" (change)="selectFile($event)" />
</label>
<button class="btn btn-success" [disabled]="!selectedFiles" (click)="upload()">
Upload
</button>
<div class="alert alert-light" role="alert">{{ message }}</div>
<div class="card">
<div class="card-header">List of Files</div>
<ul class="list-group list-group-flush">
<li *ngFor="let file of fileInfos | async" class="list-group-item">
<a href="{{ file.url }}">{{ file.name }}</a>
</li>
</ul>
</div>
Add Upload File Component to App Component
Open app.component.html and embed the UploadFile Component with <app-upload-files>
tag.
<div class="container" style="width:600px">
<div style="margin: 20px">
<h3>bezkoder.com</h3>
<h4>{{ title }}</h4>
</div>
<app-upload-files></app-upload-files>
</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 10 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 10 Client with command:
ng serve --port 8081
Open Browser with url http://localhost:8081/
and check the result.
Further Reading
- https://angular.io/api/common/http/HttpRequest
- Angular 10 CRUD Application example with Web API
- Angular 10 JWT Authentication example with Web Api
- Angular 10 Form Validation example (Reactive Forms)
Newer Versions:
– Angular 11 File upload example
– Angular 12 File upload example
– Angular 13 File upload example
– Angular 14 File upload example
– Angular 15 File upload example
Conclusion
Today we’re learned how to build an example for File upload using Angular 10 and FormData. We also provide the ability to show list of files, upload progress using Bootstrap, and to download file from the server.
Happy Learning! See you again.
Source Code
The source code for the Angular 10 Client is uploaded to Github.
If you want to upload multiple files at once like this:
You can find the instruction here:
Angular 10 Multiple Files upload example
Or multiple Images upload:
Angular 10 upload Multiple Images example
Serverless with Firebase:
Angular 10 Firebase Storage: File Upload/Display/Delete example
Hello
I just got job, and my team leader told me to do upload file from angular and send it to backend…
I dont even know what it means. This is my first job, im unexperienced
I am eager to learn but i dont know even what to learn..
They use angular 10 as frontend, spring boot as backend.
My team leader told me to add an upload button, and send info to backend..
What does it mean?
Can you help me to correct direction please? I want to learn what he asks me to do.
Thank you
Hi, you can read this tutorial:
Angular 11 + Spring Boot: File upload example
Thank you. Btw is there any way to reach you by email or something?
hi, this below code only displaying Url not displaying image, please reply as soon as possible….
{{ file.name }}
and thanks to provide always good content…
Hi, you can read this tutorial:
Angular 10 upload Multiple Images with Web API example