如何获取文件上传进度百分比并在进度条中显示
实现文件上传进度展示方案
步骤1:修改上传服务的请求配置
要获取上传进度,需在HttpClient的POST请求中开启进度报告并监听事件流,调整insertDokument方法如下:
import { HttpEvent, HttpEventType } from '@angular/common/http'; // ... insertDokument(object: any): Observable<HttpEvent<any>> { return this.http.post(this.apiRoute + '/insertDok', object, { reportProgress: true, observe: 'events' }); }
说明:
reportProgress: true开启上传进度报告observe: 'events'让请求返回事件流(而非直接返回响应体),以便捕获进度事件- 修正原POST参数顺序:将上传对象作为请求体放在第二个参数位置,配置选项放在第三个
步骤2:组件中绑定进度值到进度条
在组件类中定义进度变量,绑定到进度条的[value]属性:
组件类新增变量:
progressValue = 0;
进度条模板修改为:
<nb-progress-bar [value]="progressValue" status="primary" [displayValue]="true"></nb-progress-bar>
步骤3:修改订阅逻辑监听上传进度
更新组件的订阅代码,区分事件类型计算并更新进度:
import { HttpEvent, HttpEventType } from '@angular/common/http'; // ... this.updateDokumentSub = this.dokumentiService.insertDokument(obj) .pipe(takeUntil(this.destroy$)) .subscribe((event: HttpEvent<any>) => { // 处理上传进度事件 if (event.type === HttpEventType.UploadProgress) { this.progressValue = Math.round((100 * event.loaded) / event.total); } // 处理上传完成的响应事件 else if (event.type === HttpEventType.Response) { this.toastService.showToast('success', 'Novi dokument uspješno dodan', ''); form.resetForm(); this.close(true); this.dokumentiService.emitAddDokument(obj); this.loading = false; this.spinner.hide(); this.progressValue = 0; // 上传完成重置进度 } }, err => { console.error(err); this.loading = false; this.spinner.hide(); this.progressValue = 0; // 出错重置进度 });
说明:
- 通过
HttpEventType.UploadProgress获取已上传字节数(loaded)和总字节数(total),计算进度百分比HttpEventType.Response对应上传完成后的响应,执行原有成功逻辑- 成功/出错后重置进度值,避免影响下次上传
内容的提问来源于stack exchange,提问作者Ranko Koturic
相关产品推荐
相关产品推荐

