8

I am trying to upload files from angular. and I wanted to show the upload progress also.

upload.service.ts

public uploadProductImage(obj: FormData, id: string) {
    return this._http.post(baseUrl + `/product/upload`, obj, {
      headers: {
        product_id: id,
      },
      reportProgress : true,
      observe : 'events'
    });
  }

upload.component.ts

uploadClick() {
    const fd = new FormData();

    // for(const f of this.file_url) {
    //   fd.append('image', f.file, f.file.name);
    // }
    fd.append('image', this.file_url[0].file, this.file_url[0].file.name);
    this.service.uploadProductImage(fd, this.product_id.toString())
      .subscribe(
        event => {
          if (event.type === HttpEventType.UploadProgress) {
            console.log(event.loaded, event.total);
            this.progress = Math.round(event.loaded / event.total * 100);

          } else if (event.type === HttpEventType.Response) {
            console.log(event.body);
            this.file_url = [];
          }

        },
        err => {
          console.log(err);
        }
      );
  }

Now image uploading is working. only progress bar is not working. I am getting one event with HttpEventType.UploadProgress immediately and event.loaded and event.total both are equal.

so progressbar directly become 100 but to complete the request it take some time.

4
  • 2
    Having the very same issue, any help is appreciated Commented Sep 9, 2019 at 10:42
  • 1
    Same here, what would be the proposed solution? OP did find it? Commented Mar 15, 2020 at 3:42
  • @DARKGuy see my answer. Msy be you can find this useful Commented Mar 25, 2020 at 13:37
  • @RonaldKorze see my answer. Msy be you can find this useful Commented Mar 25, 2020 at 13:37

3 Answers 3

6

I had the same issue. For me the server is on localhost and because of that the upload was instantaneously and the progress was always 100%. Try to throttle the request in Chrome and you will see some other progress percents before the upload is completed.


The steps how to throttle the network in Chrome:

  1. Open DevTools (F12)
  2. Click the 'Network' tab
  3. Select which type of connection you want to imitate ('Slow 3G' will do the trick)
Sign up to request clarification or add additional context in comments.

2 Comments

How is this even a fix to the above question? The progress bar must be updated without modifying the throttle settings.
There is no fix for the question, because the code in the question works fine on a deployed web application. The issue with the percentage of the progress bar occured (for me) because both the web api and the angular project runs on localhost.
2

I am Using this one in a new project. and it's working. Hope it will help you

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


uploadMethod() {
        const formData: FormData = new FormData();
        formData.append('file', this.selectedFile);

        const req = new HttpRequest('POST', apiEndpoint, formData, {
          reportProgress: true,
        });

        this.http.request(req)
        .subscribe(
          (event) => {
            if (event.type === HttpEventType.UploadProgress) {
              // This is an upload progress event. Compute and show the % done:
              this.percentDone = Math.round(100 * event.loaded / event.total);
              console.log(`File is ${this.percentDone}% uploaded.`);
            } else if (event instanceof HttpResponse) {
              console.log('File is completely uploaded!');
              console.log(event.body);
            }
          },
          err => console.error(err)
        );
}

2 Comments

please explain what you have done differently than the original question. Pasting only the code that works for you isn't a good answer.
@NiamatullahBakhshi its my question and nobody has posted a good answer. If u have any answer to this please post it. I am just trying to help others. I created a new HttpRequest instance then subscribing it.
0

I was facing the same issue and in my case the cause was a custom HttpInterceptor where I used toPromise:

intercept(req: HttpRequest<any>, next: HttpHandler): any {
    return from(this.handle(req, next));
}

private async handle(req: HttpRequest<any>, next: HttpHandler) {
  try {
      return await next.handle(req).toPromise();
  } catch (err: any) {
      // error-handling logic
  }
}

After changing above code to:

intercept(req: HttpRequest<any>, next: HttpHandler){
    return next.handle(req)
      .pipe(catchError(err => {
        // error-handling logic
        return throwError(err);
      }));
  }

the issue was resolved.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.