1

Hello everyone I'm uploading file to backend and I want to get upload percentage and display it in progress bar:

Adding file ts component:

   this.updateDokumentSub = this.dokumentiService.insertDokument(obj).pipe(takeUntil(this.destroy$)).subscribe((data: any) => {
      this.toastService.showToast('success', 'Novi dokument uspješno dodan', '');
      form.resetForm();
      this.close(true);
      this.dokumentiService.emitAddDokument(obj);
      this.loading = false;
      this.spinner.hide();
    },
      err => {
        console.error(err);
        this.loading = false;
        this.spinner.hide();
      });

Service file for uploading:

  insertDokument(object: any): Observable<Object> {
    return this.http.post(this.apiRoute + '/insertDok', {
    }, object);
  }

And here is my progress bar:

   <nb-progress-bar [value]="40" status="primary" [displayValue]="true"></nb-progress-bar>

Appreciate if someone can advise. Thank you in advance!

2 Answers 2

1

You can try XMLHttpRequest to upload your file.

var formData = new FormData();
formData.append("file", 'your file');

const request = new XMLHttpRequest();
request.open('POST', 'your url');
// set authen token if you need
request.setRequestHeader('Authorization', `Bearer ${this.auth.token()}`);

request.upload.onprogress = (e) => {
  // process percent via e.lengthComputable, e.loaded, e.total
  progress(e.lengthComputable, e.loaded, e.total);
};
request.onload = () => {
  if (request.status >= 200 && request.status < 300) {
    // process when done
  } else {
    error(request.response);
  }
};
request.send(formData);

Hope this help!

Sign up to request clarification or add additional context in comments.

Comments

1

You need to change the call you an observable of HttpEvents.

  insertDokument(dokument: any): Observable<HttpEvent<Object>> {
    return this.http.post<HttpEvent<Object>>(this.apiRoute + '/insertDok', dokument, {
      reportProgress: true,
      observe: 'events',
    });
  }

The Observable emits multiple times. HttpEvent can be a HttpProgressEvent, which contains your required data. Once the upload is done the HttpEvent will change to HttpResponse.

Every HttpEvent has a typeattribute, you can use to check which event happened.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.