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.
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:
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)
);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With