How to Create File Upload Using Angular Material Tree
In this tutorial, I will show you lot way to build an Angular 12 File upload to Rest API example using Bootstrap, HttpClient, FormData and Progress Bar.
More Practice:
– Angular 12 Login and Registration case with JWT & Spider web Api
– Athwart 12 CRUD Application instance with Web API
– Athwart 12 Form Validation instance (Reactive Forms)
– Using Material: Athwart Material 12 File upload example with progress bar
Serverless with Firebase:
Athwart 12 Upload File to Firebase Storage case
Newer version: Angular 13 File upload example with progress bar & Bootstrap
Overview
Nosotros're gonna create an Angular 12 File upload to Rest API awarding in that user can:
- see the upload process (percentage)
- view all uploaded files
- download by clicking on the file name
Technology
- Angular 12
- RxJS 6
- Bootstrap 4
Rest API for File Upload & Storage
Here is the API that our Athwart App will work with:
| Methods | Urls | Actions |
|---|---|---|
| Post | /upload | upload a File |
| GET | /files | get List of Files (proper name & url) |
| GET | /files/[filename] | download a File |
You can find how to implement the Rest APIs Server at one of post-obit posts:
– Node.js Express File Upload Rest API example
– Node.js Express File Upload to MongoDB case
– Node.js Express File Upload to Google Cloud Storage example
– Spring Kick Multipart File upload (to static folder) example
Or: Leap Boot Multipart File upload (to database) example
Setup Angular 12 Project
Let's open up cmd and use Angular CLI to create a new Angular 12 Project as following command:
ng new Angular12FileUpload ? Would y'all 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 yard s services/file-upload ng yard c components/file-upload Now yous can see that our project directory construction looks like this.
Angular 12 App for uploading File with HttpClient
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 API Server using HttpClient.
– file-upload.component contains upload form, progress bar, display of listing files.
– app.component is the container that we embed all components.
– alphabetize.html for importing the Bootstrap.
Set up up App Module for HttpClient
Open app.module.ts and import HttpClientModule:
import { NgModule } from '@angular/core'; import { BrowserModule } from '@athwart/platform-browser'; import { HttpClientModule } from '@angular/mutual/http'; import { AppComponent } from './app.component'; import { FileUploadComponent } from './components/file-upload/file-upload.component'; @NgModule({ declarations: [ AppComponent, FileUploadComponent ], 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.four.1/css/bootstrap.min.css" /> </head> ... </html> Create Athwart Service for Upload Files
This service will employ Athwart HttpClient to send HTTP requests.
There are two functions:
-
upload(file): returnsObservable<HttpEvent<any>>that nosotros're gonna utilise for tracking progress -
getFiles(): returns a list of Files' information asAppreciableobject
services/file-upload.service.ts
import { Injectable } from '@athwart/core'; import { HttpClient, HttpRequest, HttpEvent } from '@angular/common/http'; import { Observable } from 'rxjs'; @Injectable({ providedIn: 'root' }) export class FileUploadService { individual baseUrl = 'http://localhost:8080'; constructor(individual http: HttpClient) { } upload(file: File): Observable<HttpEvent<any>> { const formData: FormData = new FormData(); formData.append('file', file); const req = new HttpRequest('Postal service', `${this.baseUrl}/upload`, formData, { reportProgress: true, responseType: 'json' }); return this.http.request(req); } getFiles(): Appreciable<any> { return this.http.become(`${this.baseUrl}/files`); } } – FormData is a information structure that tin exist used to shop 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. Observe that this progress event are expensive (change detection for each effect), then you should just use when yous desire to monitor information technology.
– We call the request(PostRequest) & get() method of HttpClient to send an HTTP Mail service & Get asking to the Bound Boot File Upload server.
Create Component for Upload Files
Permit's create a File Upload UI with Progress Bar, Card, Push button and Message.
Get-go nosotros demand to use the following imports:
file-upload.component.ts
import { Component, OnInit } from '@angular/core'; import { HttpEventType, HttpResponse } from '@athwart/common/http'; import { Observable } from 'rxjs'; import { FileUploadService } from 'src/app/services/file-upload.service'; And so we define the some variables and inject FileUploadService as follows:
consign course FileUploadComponent implements OnInit { selectedFiles?: FileList; currentFile?: File; progress = 0; bulletin = ''; fileInfos?: Observable<any>; constructor(private uploadService: FileUploadService) { } } Adjacent nosotros define selectFile() method. Information technology helps us to get the selected Files.
selectFile(outcome: any): void { this.selectedFiles = event.target.files; } Side by side nosotros write upload() method for upload file:
export class FileUploadComponent implements OnInit { selectedFiles?: FileList; currentFile?: File; progress = 0; message = ''; fileInfos?: Observable<any>; constructor(individual uploadService: FileUploadService) { } selectFile(event: whatsoever): void { this.selectedFiles = effect.target.files; } upload(): void { this.progress = 0; if (this.selectedFiles) { const file: File | null = this.selectedFiles.item(0); if (file) { this.currentFile = file; this.uploadService.upload(this.currentFile).subscribe( (event: any) => { if (event.type === HttpEventType.UploadProgress) { this.progress = Math.circular(100 * event.loaded / event.total); } else if (consequence instanceof HttpResponse) { this.bulletin = event.trunk.bulletin; this.fileInfos = this.uploadService.getFiles(); } }, (err: any) => { console.log(err); this.progress = 0; if (err.fault && err.error.bulletin) { this.message = err.error.message; } else { this.message = 'Could non upload the file!'; } this.currentFile = undefined; }); } this.selectedFiles = undefined; } } } We use selectedFiles for accessing current File as the first Particular. Then we call uploadService.upload() method on the currentFile.
The progress will exist calculated basing on event.loaded and event.total.
If the manual is washed, the event volition be a HttpResponse object. At this fourth dimension, nosotros call uploadService.getFiles() to get the files' information and assign the result to fileInfos variable.
We likewise need to do this piece of work in ngOnInit() method:
ngOnInit(): void { this.fileInfos = this.uploadService.getFiles(); } At present nosotros create the HTML template of the Upload File UI. Add together the following content to file-upload.component.html file:
<div course="row"> <div class="col-8"> <characterization class="btn btn-default p-0"> <input type="file" (change)="selectFile($result)" /> </label> </div> <div course="col-iv"> <button class="btn btn-success btn-sm" [disabled]="!selectedFiles" (click)="upload()"> Upload </button> </div> </div> <div *ngIf="currentFile" grade="progress my-3"> <div course="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> <div *ngIf="message" class="alert alert-secondary" role="alert">{{ message }}</div> <div class="card mt-three"> <div class="carte du jour-header">List of Files</div> <ul form="list-grouping list-group-affluent" *ngFor="allow file of fileInfos | async" > <li grade="list-group-detail"> <a href="{{ file.url }}">{{ file.name }}</a> </li> </ul> </div> Add together Upload File Component to App Component
Open up app.component.html and embed the FileUpload Component with <app-file-upload> tag.
<div class="container" style="width:600px"> <div grade="my-three"> <h3>bezkoder.com</h3> <h4>{{ title }}</h4> </div> <app-file-upload></app-file-upload> </div> app.component.ts
import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) consign class AppComponent { title = 'Angular 12 File Upload'; } Run the App
Y'all can find how to implement the Residual APIs Server at one of following posts:
– Node.js Express File Upload Remainder API example
– Node.js Limited File Upload to MongoDB example
– Node.js Express File Upload to Google Cloud Storage case
– Spring Boot Multipart File upload (to static folder) example
Because we configure CORS for origin: http://localhost:8081, so you need to run Angular 12 Client with command:
ng serve --port 8081
Open Browser with url http://localhost:8081/ and cheque the result.
Farther Reading
- https://athwart.io/api/common/http/HttpRequest
- Angular 12 Login and Registration example with JWT & Web Api
- Angular 12 Grime Application case with Web API
- Angular 12 Form Validation example (Reactive Forms)
- Angular 12 + Leap Boot: File upload case
- Athwart 12 + Node.js Express: File Upload example
Decision
Today nosotros're learned how to build an example for File upload to Rest API with Progress Bar using Angular 12 and FormData. We also provide the ability to testify listing of files, upload progress using Bootstrap, and to download file from the server.
If you want to upload multiple files at once like this:
You can find the instruction here:
Athwart 12 Multiple Files upload example with Progress Bar
Or Serverless with Firebase:
Angular Upload File to Firebase Storage case
Happy Learning! See you once again.
Source Code
The source code for the Angular 12 App is uploaded to Github.
Using Material: Athwart Fabric 12 File upload example with progress bar
Source: https://www.bezkoder.com/angular-12-file-upload/
0 Response to "How to Create File Upload Using Angular Material Tree"
Postar um comentário