Friday, November 8, 2019

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

Image upload or file upload is a common requirement of the application. In this Angular 8 tutorial we will learn File upload, file uploading progress and Image Preview. You can follow this tutorial for angular 7 also
Angular 8 File Upload or Image Upload with Preview and Progress Report

To create it open the app.component.html file and put the below html on it. Instead of app.component.html you can put on another component too!
<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>
Configure the HttpClientModule
We will use the Angular 8 HttpClient to upload the file on the server.

So before writing file upload code, first, Open src/app/app.module.ts then add this import.
import { HttpClientModule } from '@angular/common/http';
Add HttpClientModule to imports array under @NgModule
 imports: [
    HttpClientModule
]
Now open the app.component.ts file and put the below code on it
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 !!');
        })
}
After the changes our app.component.ts file will looks like this
 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 !!');
        })
  }
}
 First of all open the app.component.ts file and put the below import
import { HttpClient, HttpEventType } from '@angular/common/http';
Then you just need to add reportProgress to true and set the observe to events in the config like we have below. You will get all the events on subscribe
 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 !!');
      }
       
    })
}

No comments:

Post a Comment