Skip to content Skip to sidebar Skip to footer

multiple files in request tracking upload angularjs

In this tutorial, I will prove you lot manner to build Multiple Files upload instance using Angular 8, Bootstrap and FormData with Progress Bars.


More Practice:
– Angular 8 + Spring Boot: File upload example
– Angular eight JWT Hallmark with HttpInterceptor and Router
– Athwart 8 Crud Awarding instance with Web API

Newer Versions:
– Angular x Multiple Files upload example
– Angular 11 Multiple Files upload example
– Athwart 12 Multiple Files upload example
– Angular thirteen Multiple Files upload example

Overview

We will create an Angular Multiple Files upload application in that user can:

  • see the upload process (percent) of all uploading files
  • view all uploaded files
  • download file by clicking on the file proper name

angular-upload-multiple-files-example

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
Become /files become List of Files (name & url)
GET /files/[filename] download a File

You can discover how to implement the Rest APIs Server at one of post-obit posts:
– Node.js Express File Upload Residue API case
– Node.js Limited File Upload to MongoDB instance
– Node.js Express File Upload to Google Cloud Storage case
– Jump Kicking Multipart File upload (to static folder) example

Setup Angular 8 Projection

Let's open cmd and use Angular CLI to create a new Angular Project equally following command:

          ng new AngularUploadMultipleFiles ? Would yous like to add Angular routing? No ? Which stylesheet format would y'all like to use? CSS                  

We as well need to generate some Components and Services:

          ng one thousand s services/upload-files   ng thou c components/upload-files                  

Now you tin run across that our projection directory structure looks similar this.

Angular 8 App for upload File

angular-upload-multiple-files-example-project-structure

Let me explain it briefly.

– Nosotros import necessary library, components in app.module.ts.
upload-files.service provides methods to save File and get Files from Residuum Apis Server.
upload-files.component contains upload multiple files form, some progress confined, display of list files.
app.component is the container that we embed all components.
index.html for importing the Bootstrap.

Fix App Module

Open up app.module.ts and import HttpClientModule:

          import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@athwart/cadre'; import { AppComponent } from './app.component'; import { HttpClientModule } from '@angular/common/http'; import { UploadFilesComponent } from './components/upload-files/upload-files.component'; @NgModule({   declarations: [     AppComponent,     UploadFilesComponent   ],   imports: [     BrowserModule,     HttpClientModule   ],   providers: [],   bootstrap: [AppComponent] }) consign form AppModule { }                  

Add Bootstrap to the project

Open index.html and add following line into <caput> tag:

          <!DOCTYPE html> <html lang="en">   <head>     ...     <link type="text/css" rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.iv.1/css/bootstrap.min.css" />   </head>   ... </html>                  

Create Athwart Service for Upload Multiple Files

This service will apply Angular HTTPClient to send HTTP requests.
There are 2 functions:

  • upload(file): returns Observable<HttpEvent<whatever>> that nosotros're gonna apply for tracking progress
  • getFiles(): returns a list of Files' information as Observable object

services/upload-files.service.ts

          import { Injectable } from '@angular/cadre'; import { HttpClient, HttpRequest, HttpEvent } from '@angular/mutual/http'; import { Observable } from 'rxjs'; @Injectable({   providedIn: 'root' }) export class UploadFilesService {   individual baseUrl = 'http://localhost:8080';   constructor(individual http: HttpClient) { }   upload(file: File): Observable<HttpEvent<whatsoever>> {     const formData: FormData = new FormData();     formData.append('file', file);     const req = new HttpRequest('Mail service', `${this.baseUrl}/upload`, formData, {       reportProgress: true,       responseType: 'json'     });     render this.http.asking(req);   }   getFiles(): Observable<any> {     render this.http.get(`${this.baseUrl}/files`);   } }                  

FormData is a information construction that can be used to store key-value pairs. Nosotros use it to build an object which corresponds to an HTML form with append() method.

– We fix reportProgress: true to exposes progress events. Notice that this progress result are expensive (change detection for each event), so you should but use when you want to monitor information technology.

– We phone call the request(PostRequest) & go() method of HttpClient to transport an HTTP POST & Get request to the Multiple Files Upload Rest server.

Create Angular Component for Upload Multiple Files

Permit'south create a Multiple Files Upload UI with Progress Bars, Carte du jour, Push button and Bulletin.

First we need to use the following imports:

upload-files.component.ts

          import { Component, OnInit } from '@angular/core'; import { UploadFilesService } from 'src/app/services/upload-files.service'; import { HttpEventType, HttpResponse } from '@angular/mutual/http'; import { Observable } from 'rxjs';                  

Then nosotros define the some variables and inject UploadFilesService equally follows:

          export class UploadFilesComponent implements OnInit {   selectedFiles: FileList;   progressInfos = [];   message = '';   fileInfos: Appreciable<any>;   constructor(private uploadService: UploadFilesService) { } }                  

The progressInfos is an array that contains items for display upload progress of each files. Each item will have 2 fields: value & fileName.

Next we define selectFiles() method. It helps us to go the selected Files that we're gonna upload.

          selectFiles(effect) {   this.progressInfos = [];   this.selectedFiles = event.target.files; }                  

Now we iterate over the selected Files higher up and call upload() method on each file item.

          uploadFiles() {   this.message = '';   for (permit i = 0; i < this.selectedFiles.length; i++) {     this.upload(i, this.selectedFiles[i]);   } }                  

Next we define upload() method for uploading each file:

          upload(idx, file) {   this.progressInfos[idx] = { value: 0, fileName: file.name };   this.uploadService.upload(file).subscribe(     result => {       if (event.type === HttpEventType.UploadProgress) {         this.progressInfos[idx].value = Math.round(100 * upshot.loaded / outcome.total);       } else if (effect instanceof HttpResponse) {         this.fileInfos = this.uploadService.getFiles();       }     },     err => {       this.progressInfos[idx].value = 0;       this.bulletin = 'Could not upload the file:' + file.name;     }); }                  

We use idx for accessing alphabetize of the current File to work with progressInfos assortment. So we phone call uploadService.upload() method on the file.

The progress volition exist calculated basing on event.loaded and event.total.
If the manual is done, the result volition be a HttpResponse object. At this fourth dimension, we call uploadService.getFiles() to become the files' data and assign the result to fileInfos variable.

Nosotros too need to practice 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-files.component.html file:

          <div *ngFor="let progressInfo of progressInfos" class="mb-ii">   <span>{{ progressInfo.fileName }}</span>   <div class="progress">     <div       grade="progress-bar progress-bar-info progress-bar-striped"       role="progressbar"       attr.aria-valuenow="{{ progressInfo.value }}"       aria-valuemin="0"       aria-valuemax="100"       [ngStyle]="{ width: progressInfo.value + '%' }"     >       {{ progressInfo.value }}%     </div>   </div> </div> <label class="btn btn-default">   <input blazon="file" multiple (change)="selectFiles($upshot)" /> </label> <push   grade="btn btn-success"   [disabled]="!selectedFiles"   (click)="uploadFiles()" >   Upload </button> <div class="warning alert-lite" role="alert">{{ message }}</div> <div course="bill of fare">   <div form="card-header">List of Files</div>   <ul     form="list-grouping list-group-flush"     *ngFor="permit file of fileInfos | async"   >     <li class="list-group-item">       <a href="{{ file.url }}">{{ file.name }}</a>     </li>   </ul> </div>                  

Add Upload Multiple Files Component to App Component

Open app.component.html and embed the UploadFile Component with <app-upload-files> tag.

          <div grade="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 '@athwart/core'; @Component({   selector: 'app-root',   templateUrl: './app.component.html',   styleUrls: ['./app.component.css'] }) export course AppComponent {   championship = 'Angular Upload Multiple Files'; }                  

Run the App

If y'all utilize ane of following server:
- Node.js Express File Upload Rest API case
- Node.js Express File Upload to MongoDB example
- Node.js Express File Upload to Google Deject Storage example
- Spring Kick Multipart File upload (to static binder) example

You demand run with port 8081 for CORS origin http://localhost:8081 with command:
ng serve --port 8081

Open Browser with url http://localhost:8081/ and bank check the outcome.

Farther Reading

  • https://angular.io/api/common/http/HttpRequest
  • Athwart eight JWT Authentication with HttpInterceptor and Router
  • Angular 8 Crud Awarding instance with Web API

Newer Versions:
- Angular 10 Multiple Files upload example
- Angular 11 Multiple Files upload example
- Angular 12 Multiple Files upload case
- Angular thirteen Multiple Files upload example

Decision

Today we're learned how to build an example for multiple Files upload using Athwart 8 and FormData. We also provide the ability to show list of files, multiple progress bars using Bootstrap.

You can find how to implement the Residual APIs Server at ane of following posts:
- Node.js Express File Upload Balance API example
- Node.js Express File Upload to MongoDB case
- Node.js Express File Upload to Google Cloud Storage case
- Spring Kick Multipart File upload (to static folder) example

If you want to upload multiple images like this:

angular-8-upload-multiple-images-example

You can observe the instruction here:
Athwart viii upload Multiple Images example

Source Lawmaking

The source lawmaking for the Athwart viii Client is uploaded to Github.

silversteinonch1942.blogspot.com

Source: https://www.bezkoder.com/angular-multiple-files-upload/

Post a Comment for "multiple files in request tracking upload angularjs"