Tarnjeet Singh
Tarnjeet Singh

Reputation: 896

How to track file upload progress and get url of uploaded file as well in angular 5

I am working on angular 5 application. In which, I have requirement to upload a image and track progress of upload. I also need to get the response of file upload api. Here is my code:

upload(){

      const fd = new FormData();
      fd.append('file', this.selectedFile, this.selectedFile.name);

      this.uploadImageApi(fd).subscribe(res => {this.apiResponse = res},
                                                      err => console.log(err),
                                                      ()  => this.checkUploadApiResponse(this.apiResponse, window)
                                                     );
     }

Check response function :

checkUploadApiResponse(response: any, window: Window)
{
    console.log(response);
}

Api Function :

uploadImageApi(fd: any)
{
    return this.http.post<Response>('url', fd).map(response => response.response);
}

Upvotes: 0

Views: 2499

Answers (2)

Anuradha Gunasekara
Anuradha Gunasekara

Reputation: 6983

You can do that by Listening to progress events as mentioned in the official documentation

What you have to dp is writing a service function that returns Observable<HttpEvent<any>> like this.

public uploadFile(file: File): Observable<HttpEvent<any>> {
    const formData: FormData = new FormData();
    formData.append('uploadingFile', file, file.name);
    const req = new HttpRequest('POST', 'url', formData, {
      reportProgress: true
    });
    return this.http.request(req);
  }

and inject the service to the component that you use to select and upload the file.

public uploadFile(): void {
    if (this.file) {
      this.uploadSubscription = this.uploadServiceService
        .uploadFile(this.file)
        .pipe(map((data) => {
            this.getEventMessage(data, this.file);
          }),
          last())
        .subscribe(() => {

        }, () => {
          // on error
          this.percentage = 0;
        });
    }
  }

private getEventMessage(event: HttpEvent<any>) {
    switch (event.type) {
      case HttpEventType.Sent:
        this.percentage = 0;  // upload percentage
        break;

      case HttpEventType.UploadProgress:
        const percentDone = Math.round(100 * event.loaded / event.total);
        this.percentage = percentDone;
        break;

      case HttpEventType.Response:
        this.percentage = 100; // file is uploaded
        if (check the event status in here) {   // event.body 
          // show notifications/toast in here
          return;
        }
    }
  }

you can use percentage to show the percentage usng a progress bar. And using event.body you can get the backend response.

you can write a file upload cancel function like this.

public cancelFileUpload(): void {
    if (this.uploadSubscription) {
      this.uploadSubscription.unsubscribe();
    }
  }

Upvotes: 1

Chellappan வ
Chellappan வ

Reputation: 27471

You can use Progress event to check Upload Status!

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

http.request(new HttpRequest(
  'POST',
  URL,
  body, 
  {
    reportProgress: true
  })).subscribe(event => {

  if (event.type === HttpEventType.DownloadProgress) {
     {
     }
  }

  if (event.type === HttpEventType.UploadProgress) {
     {
      }
  }

  if (event.type === HttpEventType.Response) {
    console.log(event.body);
  }

})

Upvotes: 1

Related Questions