Aakash
Aakash

Reputation: 3171

How do I access the HttpEvent progress for file upload in Angular 5?

I have been through the angular.io docs as well as other SO answers on this however I still cant wrap my head around how to access file upload progress for my POST call from Angular 5 to NodeJS and display to the user.

Here is what I am doing.

//Component Code: body is the form data that has a file and a few other fields.

  this.fileService.uploadtool5(body, this.token).subscribe(res =>{

        if(res.success){
          //do something server has received post data
        }
      },(err: HttpErrorResponse) => {
        if (err.error instanceof Error) {
              // A client-side or network error occurred. Handle it accordingly.
              //console.log('An error occurred:', err.error.message);
              //console.log('Status', err.status);
             // this.signupfailreasonstatus = err.status;
            } else {
              // The backend returned an unsuccessful response code.
              // The response body may contain clues as to what went wrong,
              //console.log(`Backend returned code ${err.status}, body was: ${err.error}`);
              //console.log('Status', err.status);
            }
      });

//I have an interceptor for the response object which looks like this.

export interface Tool9Response {
  success: boolean;
  message: string;
} 

//fileService code

uploadtool5( payload, token ) : Observable<Tool9Response>{
       const httpOptions = {
         headers: new HttpHeaders({
           'Authorization': token
         })
       };
       return this.http.post<Tool9Response>(this._baseURL + 'appsecuritydesign', payload, httpOptions);

   }

Most of the files that I am uploading are 100+ MB for processing so upload takes time and I want to show the upload progress. How do I access the HttpEvent progress for the file upload without changing how I am currently posting the data to the server?

Upvotes: 2

Views: 2468

Answers (1)

Ritwick Dey
Ritwick Dey

Reputation: 19012

In your fileService code:

uploadtool5( payload, token ) : Observable<any> { // Assuming `payload` is FormData 

    const headers = new HttpHeaders({
       'Authorization': token
     })


   const req = new HttpRequest(
        'POST',      
         this._baseURL + 'appsecuritydesign', 
         payload, 
         { 
            headers:headers,
            reportProgress: true //This is required for track upload process
         }
   );

   return this.http.request(req);
 }

// component

this.fileService.uploadtool5(body, this.token).subscribe((event: HttpEvent<any>) => {

   if (event.type == HttpEventType.UploadProgress)
   {
     console.log("Loading: "+ event.loaded / (event.total || event.loaded) * 100 + '%');
   }
   if (event.type == HttpEventType.Response) {
     console.log("response:", event);
    /*success and message fields from the response can be accessed 
      here like this*/
     console.log("response:", event);
     console.log("body:", event.body);
     console.log("success:", event.body.success);
     console.log("message:", event.body.message);
   }


  });

Upvotes: 4

Related Questions