You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何获取文件上传进度百分比并在进度条中显示

实现文件上传进度展示方案

步骤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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 15:35:23