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

基于ABP框架的Angular端RestService文件上传进度实现方案咨询

Angular 中使用 RestService 实现文件上传进度监控

1. 封装带进度监听的上传服务

在你的 RestService 中扩展上传方法,利用 Angular HttpClient 的reportProgress配置捕获上传进度事件,通过事件流返回进度数据:

import { Injectable } from '@angular/core';
import { HttpClient, HttpRequest, HttpEvent, HttpEventType } from '@angular/common/http';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';

@Injectable({ providedIn: 'root' })
export class RestService {
  private baseApiUrl = '你的后端API根地址';

  constructor(private http: HttpClient) {}

  uploadFile(file: File): Observable<{ progress: number; fileName?: string }> {
    const formData = new FormData();
    formData.append('file', file);

    // 构建带进度监听的请求
    const uploadReq = new HttpRequest(
      'POST',
      `${this.baseApiUrl}/UploadFile`,
      formData,
      {
        reportProgress: true,
        responseType: 'text' // 匹配后端返回的字符串类型文件名
      }
    );

    return this.http.request(uploadReq).pipe(
      map((event: HttpEvent<any>) => {
        switch (event.type) {
          case HttpEventType.UploadProgress:
            // 计算上传进度百分比
            const progressPercent = Math.round((100 * event.loaded) / (event.total || 1));
            return { progress: progressPercent };
          case HttpEventType.Response:
            // 上传完成,返回后端返回的文件名
            return { progress: 100, fileName: event.body };
          default:
            return { progress: 0 };
        }
      })
    );
  }
}

2. 组件中调用服务并更新进度UI

在组件中绑定文件选择事件,订阅上传流来实时更新进度:

import { Component } from '@angular/core';
import { RestService } from './rest.service';

@Component({
  selector: 'app-file-upload',
  template: `
    <input type="file" (change)="handleFileSelect($event)">
    <div class="progress-container" *ngIf="uploadProgress > 0">
      <div class="progress-bar" [style.width.%]="uploadProgress"></div>
      <span>{{ uploadProgress }}%</span>
    </div>
    <p *ngIf="uploadedFileName">上传完成,存储文件名:{{ uploadedFileName }}</p>
  `,
  styles: [`
    .progress-container { height: 20px; border: 1px solid #ccc; margin: 10px 0; }
    .progress-bar { height: 100%; background: #4CAF50; width: 0; transition: width 0.3s; }
  `]
})
export class FileUploadComponent {
  uploadProgress = 0;
  uploadedFileName?: string;

  constructor(private restService: RestService) {}

  handleFileSelect(event: Event) {
    const selectedFile = (event.target as HTMLInputElement).files?.[0];
    if (!selectedFile) return;

    this.uploadProgress = 0;
    this.uploadedFileName = undefined;

    this.restService.uploadFile(selectedFile).subscribe({
      next: (res) => {
        this.uploadProgress = res.progress;
        if (res.fileName) {
          this.uploadedFileName = res.fileName;
        }
      },
      error: (err) => {
        console.error('上传失败:', err);
        // 可添加错误提示逻辑
      }
    });
  }
}

3. 后端适配说明

你的后端UploadFile方法无需修改核心逻辑,只需确保:

  • API路由与前端请求地址一致(示例中为/UploadFile)
  • 后端返回的文件名是纯字符串格式,匹配前端responseType: 'text'的配置

内容的提问来源于stack exchange,提问作者Idrees

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 17:35:14