Javascript required
Skip to content Skip to sidebar Skip to footer

How to Do Image Preview of What You Uploaded Using Angular 2

In this tutorial, I will show you lot manner to build Angular 13 Image Upload with Preview example (Multiple Images) with Web API/Residual API, FormData and Bootstrap Progress Confined.

More Practice:
– Angular + Spring Kick: File upload example
– Angular + Node Express: File Upload example
– Angular CRUD Application with Residue API
– Angular Login and Registration instance with Web Api
– Using Textile: Angular Material Paradigm upload with Preview example

Overview

We will create an Angular xiii Paradigm upload with Preview awarding in that user can:

  • upload multiple Images
  • see the preview of images that will be uploaded
  • see the upload process (percentage) of all uploading images
  • view all uploaded images
  • download paradigm by clicking on the file name

Here are screenshots of our React App:

– Before upload:

angular-13-image-upload-preview-example-before-upload

– When Image Upload is done:

angular-13-image-upload-preview-example

– List of Images Display with download Urls:

angular-13-image-upload-preview-example-list-images

– Testify condition for each image upload:

angular-13-image-upload-preview-example-upload-status

Technology

  • Angular 13
  • RxJS 7
  • Bootstrap 4

Residual API for Image Upload & Storage

Here are Rest APIs that we will use Axios to brand HTTP requests:

Methods Urls Deportment
Mail /upload upload a File
GET /files get Listing of Files (name & url)
Go /files/[filename] download a File

You tin find how to implement the Balance APIs Server at 1 of following posts:
– Node.js Limited File Upload Rest API instance
– Node.js Limited File Upload to MongoDB example
– Node.js Express File Upload to Google Cloud Storage example
– Jump Kick Multipart File upload (to static folder) example

Setup Athwart 13 Paradigm Upload Preview Project

Let's open up cmd and use Athwart CLI to create a new Athwart Projection as following command:

          ng new Angular13ImageUploadPreview ? Would you like to add Angular routing? No ? Which stylesheet format would you similar to use? CSS                  

Nosotros as well need to generate some Components and Services:

          ng thou due south services/file-upload ng g c components/upload-images                  

Now you lot tin come across that our project directory structure looks similar this.

Angular 13 Image upload with Preview Project

angular-13-image-upload-preview-example-project-structure

Let me explain it briefly.

– Nosotros 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 image upload for 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 Bootstrap.

Gear up App Module

Open app.module.ts and import HttpClientModule:

          import { NgModule } from '@athwart/core'; import { BrowserModule } from '@angular/platform-browser'; import { HttpClientModule } from '@athwart/mutual/http'; import { AppComponent } from './app.component'; import { UploadImagesComponent } from './components/upload-images/upload-images.component'; @NgModule({   declarations: [     AppComponent,     UploadImagesComponent   ],   imports: [     BrowserModule,     HttpClientModule   ],   providers: [],   bootstrap: [AppComponent] }) export class AppModule { }                  

Add together Bootstrap to the projection

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

          <!DOCTYPE html> <html lang="en">   <head>     ...     <link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/css/bootstrap.min.css" />   </head>   ... </html>                  

Create Angular Service for Upload Files

This service will use Angular HttpClient to transport HTTP requests.
There are 2 functions:

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

services/file-upload.service.ts

          import { Injectable } from '@angular/core'; import { HttpClient, HttpRequest, HttpEvent } from '@angular/mutual/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('Mail', `${this.baseUrl}/upload`, formData, {       reportProgress: true,       responseType: 'json'     });     return this.http.asking(req);   }   getFiles(): Observable<any> {     return this.http.get(`${this.baseUrl}/files`);   } }                  

FormData is a data structure that can be used to shop key-value pairs. We use it to build an object which corresponds to an HTML form with append() method.

– We fix reportProgress: true to exposes progress events. Discover that this progress result are expensive (modify detection for each event), and so yous should only use when you want to monitor it.

– We telephone call the request(PostRequest) & become() method of HttpClient to send an HTTP Mail & Get request to the Multiple Files Upload Rest server.

Create Angular xiii Component for Upload Multiple Images

Permit's create a Multiple Images Upload UI with Preview, Progress Confined, Card, Button and Message.

Commencement nosotros need to use the following imports:

upload-images.component.ts

          import { Component, OnInit } from '@athwart/core'; import { HttpEventType, HttpResponse } from '@angular/common/http'; import { Observable } from 'rxjs'; import { FileUploadService } from 'src/app/services/file-upload.service';                  

And so we ascertain the some variables and inject FileUploadService equally follows:

          export class UploadImagesComponent implements OnInit {   selectedFiles?: FileList;   progressInfos: whatever[] = [];   message: string[] = [];   previews: string[] = [];   imageInfos?: Appreciable<any>;   constructor(private uploadService: FileUploadService) { } }                  

The progressInfos is an array that contains items for display upload progress of each images. Each detail will accept 2 fields: per centum & fileName.

Next we define selectFiles() method. It helps united states to become the selected Images that we're gonna upload.

          selectFiles(event: whatsoever): void {   this.message = [];   this.progressInfos = [];   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 = (eastward: any) => {         console.log(e.target.event);         this.previews.button(e.target.outcome);       };       reader.readAsDataURL(this.selectedFiles[i]);     }   } }                  

We use FileReader with readAsDataURL() method to get the paradigm 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 certificate in the window on which it was created.

Also utilise selectedFiles array for accessing current selected Files.

Now we iterate over the selected Files above and telephone call upload() method on each file particular.

          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.proper noun };   if (file) {     this.uploadService.upload(file).subscribe({       side by side: (event: any) => {         if (upshot.type === HttpEventType.UploadProgress) {           this.progressInfos[idx].value = Math.round(100 * event.loaded / upshot.full);         } else if (event instanceof HttpResponse) {           const msg = 'Uploaded the file successfully: ' + file.proper noun;           this.bulletin.push(msg);           this.imageInfos = this.uploadService.getFiles();         }       },       mistake: (err: any) => {         this.progressInfos[idx].value = 0;         const msg = 'Could not upload the file: ' + file.proper noun;         this.message.push(msg);       }});   } }                  

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

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

We also need to exercise this work in ngOnInit() method:

          ngOnInit(): void {   this.imageInfos = this.uploadService.getFiles(); }                  

Now nosotros create the HTML template of the Image Upload with Preview UI.
Add the following content to upload-images.component.html file:

          <div *ngFor="let progressInfo of progressInfos" class="mb-ii">   <span>{{ progressInfo.fileName }}</span>   <div class="progress">     <div       class="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> <div class="row">   <div course="col-viii">     <label class="btn btn-default p-0">       <input blazon="file" have="prototype/*" multiple (modify)="selectFiles($result)" />     </label>   </div>   <div class="col-iv">     <button       grade="btn btn-success btn-sm"       [disabled]="!selectedFiles"       (click)="uploadFiles()"     >       Upload     </button>   </div> </div> <div>   <img *ngFor='let preview of previews' [src]="preview" class="preview"> </div> <div *ngIf="message.length" course="warning alert-secondary my-3" role="alert">   <ul *ngFor="let msg of message; let i = index">     <li>{{ msg }}</li>   </ul> </div> <div grade="card mt-three">   <div class="bill of fare-header">Listing of Images</div>   <ul     form="list-group listing-group-flush"     *ngFor="allow image of imageInfos | async"   >     <li class="listing-grouping-particular">       <p><a href="{{ image.url }}">{{ prototype.name }}</a></p>       <img src="{{ image.url }}" alt="{{ image.name }}" height="80px" />     </li>   </ul> </div>                  

upload-images.component.css

          .preview {   max-width: 200px; }                  

Add Upload Images Component to App Component

Open up app.component.html and embed the Upload Images Component with <app-upload-images> tag.

          <div class="container" manner="width:650px">   <div class="my-3">     <h3>bezkoder.com</h3>     <h4>{{ title }}</h4>   </div>   <app-upload-images></app-upload-images> </div>                  

app.component.ts

          import { Component } from '@angular/cadre'; @Component({   selector: 'app-root',   templateUrl: './app.component.html',   styleUrls: ['./app.component.css'] }) export form AppComponent {   title = 'Angular 13 Prototype Upload with Preview'; }                  

Run the App

If you use one of post-obit server:
– Node.js Express File Upload Balance API example
– Node.js Limited File Upload to MongoDB instance
– Node.js Express File Upload to Google Deject Storage example
– Jump Kick 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 up Browser with url http://localhost:8081/ and bank check the result.

Or run on Stackblitz:

Further Reading

  • https://angular.io/api/common/http/HttpRequest
  • Angular + Spring Boot: File upload example
  • Angular + Node Express: File Upload instance
  • Angular CRUD Application with Rest API
  • Athwart Login and Registration example with Web Api
  • Angular Form Validation example (Reactive Forms)

Using Fabric: Angular Material Image upload with Preview example

Decision

Today nosotros're learned how to build an instance for (multiple) Image upload with preview using Angular 13 and Bootstrap 4. Nosotros also provide the ability to testify list of images and brandish multiple progress confined.

Yous tin 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 instance
– Node.js Express File Upload to Google Cloud Storage example
– Bound Boot Multipart File upload (to static binder) case

The source lawmaking for the Angular 13 Client is uploaded to Github.

whittellwared1999.blogspot.com

Source: https://www.bezkoder.com/angular-13-image-upload-preview/