Image uploader in Angular with Preview & Progress

Today, We want to share with you angular image uploader.In this post we will show you angular image upload, hear for Angular 8 tutorial we will learn File upload, file uploading progress and Image Preview we will give you demo and example for implement.In this post, we will learn about Multiple File Upload with Validation with an example.

Angular 8 File Upload or Image Upload with Preview and Progress Report

Create template

Setp 1: app.component.html

<div class="container">
    <div class="row">
        <div class="col-md-6 offset-md-3">
            <h3>Choose File</h3>            
            <div class="form-group">
                <input type="file" name="image" (change)="fileProgress($event)" />
            </div>
            <div *ngIf="fileUploadProgress">
                Upload progress: {{ fileUploadProgress }}
            </div>
            <div class="image-preview mb-3" *ngIf="previewUrl">
                <img [src]="previewUrl" height="300" />                 
            </div>
 
            <div class="mb-3" *ngIf="uploadedFilePath">
                {{uploadedFilePath}}
            </div>
             
            <div class="form-group">
                <button class="btn btn-primary"  (click)="onSubmit()">Submit</button>
            </div>
        </div>
    </div>
</div>

Free Live Chat for Any Issue

Configure the HttpClientModule

step 2: src/app/app.module.ts

import { HttpClientModule } from '@angular/common/http';

Add HttpClientModule to imports array under @NgModule

Also Read This πŸ‘‰   Ng-Bind Directive using Angular Example

imports: [
    HttpClientModule
]

app.component.ts

fileData: File = null;
previewUrl:any = null;
fileUploadProgress: string = null;
uploadedFilePath: string = null;
constructor(private http: HttpClient) { }
 
fileProgress(fileInput: any) {
      this.fileData = <File>fileInput.target.files[0];
      this.preview();
}
 
preview() {
    // Show preview 
    var mimeType = this.fileData.type;
    if (mimeType.match(/image\/*/) == null) {
      return;
    }
 
    var reader = new FileReader();      
    reader.readAsDataURL(this.fileData); 
    reader.onload = (_event) => { 
      this.previewUrl = reader.result; 
    }
}
 
onSubmit() {
    const formData = new FormData();
      formData.append('file', this.fileData);
      this.http.post('url/to/your/api', formData)
        .subscribe(res => {
          console.log(res);
          this.uploadedFilePath = res.data.filePath;
          alert('SUCCESS !!');
        })
}

Update our app.component.ts

import { Component, OnInit } from '@angular/core';
import { HttpClient, HttpEventType } from '@angular/common/http';
 
@Component({
  selector: 'app-image-upload-with-preview',
  templateUrl: './image-upload-with-preview.component.html',
  styleUrls: ['./image-upload-with-preview.component.css']
})
 
export class ImageUploadWithPreviewComponent implements OnInit {
 
  fileData: File = null;
  previewUrl:any = null;
  fileUploadProgress: string = null;
  uploadedFilePath: string = null;
  constructor(private http: HttpClient) { }
   
  ngOnInit() {
  }
   
  fileProgress(fileInput: any) {
      this.fileData = <File>fileInput.target.files[0];
      this.preview();
  }
 
  preview() {
    // Show preview 
    var mimeType = this.fileData.type;
    if (mimeType.match(/image\/*/) == null) {
      return;
    }
 
    var reader = new FileReader();      
    reader.readAsDataURL(this.fileData); 
    reader.onload = (_event) => { 
      this.previewUrl = reader.result; 
    }
  }
   
  onSubmit() {
      const formData = new FormData();
      formData.append('file', this.fileData);
      this.http.post('url/to/your/api', formData)
        .subscribe(res => {
          console.log(res);
          this.uploadedFilePath = res.data.filePath;
          alert('SUCCESS !!');
        }) 
  }
}

app.component.ts file and put the below import

Also Read This πŸ‘‰   Angularjs ng-keypress Event Handling Directive

import { HttpClient, HttpEventType } from '@angular/common/http';

add reportProgress to true and set the observe to events in the config

onSubmit() {
    const formData = new FormData();
    formData.append('files', this.fileData);
     
    this.fileUploadProgress = '0%';
 
    this.http.post('https://us-central1-tutorial-e6ea7.cloudfunctions.net/fileUpload', formData, {
      reportProgress: true,
      observe: 'events'   
    })
    .subscribe(events => {
      if(events.type === HttpEventType.UploadProgress) {
        this.fileUploadProgress = Math.round(events.loaded / events.total * 100) + '%';
        console.log(this.fileUploadProgress);
      } else if(events.type === HttpEventType.Response) {
        this.fileUploadProgress = '';
        console.log(events.body);          
        alert('SUCCESS !!');
      }
         
    }) 
}

I hope you get an idea about Image upload or file upload.
I would like to have feedback on my infinityknow.com blog.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.