ahmed elbarbary

ahmed elbarbary

  • NA
  • 1.6k
  • 254.1k

error on event.total object possibly is undefined when Upload file?

Nov 13 2020 6:02 PM
I work on Angular 7 I face issue event.total give me error as below :
(property) HttpProgressEvent.total?: number | undefined
Total number of bytes to upload or download. Depending on the request or response, this may not be
computable and thus may not be present.
Object is possibly 'undefined'.ts(2532)
I done This Component for upload files .
so How to solve this issue
 
  1. import { Component, OnInit, EventEmitter, Output } from '@angular/core';  
  2. import { HttpClient, HttpEventType,HttpProgressEvent } from '@angular/common/http';  
  3.   
  4. @Component({  
  5.   selector: 'app-delivery-files',  
  6.   templateUrl: './delivery-files.component.html',  
  7.   styleUrls: ['./delivery-files.component.css']  
  8. })  
  9.   
  10. export class DeliveryFilesComponent implements OnInit  {  
  11.   
  12.     
  13.   @Output() public onUploadFinished = new EventEmitter();  
  14.     
  15.   constructor(private http: HttpClient,public progress: number,public message: string) { }  
  16.   ngOnInit() {  
  17.   }  
  18.     
  19.   public uploadFile = (files:any) => {  
  20.     if (files.length === 0) {  
  21.       return;  
  22.     }  
  23.       
  24.     let fileToUpload = <File>files[0];  
  25.     const formData = new FormData();  
  26.     formData.append('file', fileToUpload, fileToUpload.name);  
  27.       
  28.     this.http.post('https://localhost:5001/api/upload', formData, {reportProgress: true, observe: 'events'})  
  29.       .subscribe(event => {  
  30.         if (event.type === HttpEventType.UploadProgress)  
  31.           this.progress = Math.round(100 * event.loaded / event.total);  
  32.         else if (event.type === HttpEventType.Response) {  
  33.           this.message = 'Upload success.';  
  34.           this.onUploadFinished.emit(event.body);  
  35.         }  
  36.       });  
 

Answers (1)