Angular file upload progress percentage [duplicate]
This works in Angular 9 and 10 (note observe: 'events'
)
const headers = new HttpHeaders({ 'Content-Type': 'application/json', Accept: 'application/json', Authorization: token }))const formData = new FormData();formData.append('file_param_name', file, file.name);this.httpClient.post(url, formData, { headers, reportProgress: true, observe: 'events'}).subscribe(resp => { if (resp.type === HttpEventType.Response) { console.log('Upload complete'); } if (resp.type === HttpEventType.UploadProgress) { const percentDone = Math.round(100 * resp.loaded / resp.total); console.log('Progress ' + percentDone + '%'); } });
uploadDocument(file) { return this.httpClient.post(environment.uploadDocument, file, { reportProgress: true, observe: 'events' })}
You can easily achieve this with:
npm i angular-progress-http
After importing the module, you can now add below it to your app.module.ts or wherever you stack your app modules in your application.
You will import this (in app.module.ts):
import { HttpModule } from '@angular/http';import { ProgressHttpModule } from 'angular-progress-http';
Still in your app.module.ts
at @NgModule
@NgModule({ imports: [ HttpModule, ProgressHttpModule ]})
Then in your component file (whatever.component.ts), where you want to use it. You can place this:
import { ProgressHttp } from 'angular-progress-http';
Then implement like this:
constructor(private http: ProgressHttp) {} onSubmit(): void { const _formData = new FormData(); _formData.append('title', this.title); _formData.append('doc', this.doc); this.http.withUploadProgressListener(progress => { console.log(`Uploading ${progress.percentage}%`); }) .withDownloadProgressListener(progress => { console.log(`Downloading ${progress.percentage}%`); }) .post('youruploadurl', _formData) .subscribe((response) => { console.log(response); }); }