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

Angular中如何限制HTTP请求并发数?上传100图仅5个同时请求

Angular 实现最多5个并发图片上传请求控制

要实现最多同时执行5个上传请求,完成一个自动补全下一个的需求,直接用Angular依赖的RxJS就能搞定,核心是利用mergeMap操作符的并发控制能力,具体实现步骤如下:

1. 封装单个图片上传方法

先写一个基础的单图上传函数,返回Observable(Angular的HttpClient本身就返回Observable):

import { HttpClient, HttpEventType } from '@angular/common/http';
import { Observable } from 'rxjs';
import { filter, map } from 'rxjs/operators';

// 注入HttpClient
constructor(private http: HttpClient) {}

// 单个图片上传,可选返回进度
private uploadSingleImage(file: File): Observable<any> {
  const formData = new FormData();
  formData.append('image', file);

  // 如果需要跟踪上传进度,添加reportProgress配置
  return this.http.post('/api/upload', formData, {
    reportProgress: true,
    observe: 'events'
  }).pipe(
    filter(event => event.type === HttpEventType.UploadProgress || event.type === HttpEventType.Response),
    map(event => {
      if (event.type === HttpEventType.UploadProgress) {
        const progress = Math.round((100 * event.loaded) / (event.total || 1));
        return { type: 'progress', filename: file.name, progress };
      } else {
        return { type: 'complete', filename: file.name, result: event.body };
      }
    })
  );
}

2. 批量上传并控制并发

用from把100个文件的数组转成Observable流,再通过mergeMap设置并发数为5,就能自动维持最多5个请求同时执行:

import { from } from 'rxjs';
import { mergeMap, catchError } from 'rxjs/operators';

uploadBatchImages(imageFiles: File[]) {
  // 将文件数组转为逐个发射的Observable
  return from(imageFiles).pipe(
    // 关键:第二个参数设置并发数为5
    mergeMap(file => this.uploadSingleImage(file), 5),
    // 处理单个上传失败的情况,避免整个批量流程中断
    catchError((error, caught$) => {
      console.error(`上传失败: ${error.message}`);
      return caught$; // 继续处理剩余文件
    })
  );
}

3. 调用批量上传方法

在需要触发上传的地方调用,订阅结果即可:

// 假设imageFiles是包含100个File的数组
this.uploadBatchImages(this.imageFiles).subscribe({
  next: (res) => {
    if (res.type === 'progress') {
      console.log(`[${res.filename}] 上传进度: ${res.progress}%`);
    } else {
      console.log(`[${res.filename}] 上传完成`, res.result);
    }
  },
  complete: () => {
    console.log('所有图片上传流程结束');
  }
});

原理说明

  • from(imageFiles):把文件数组转换成一个Observable,会逐个发射数组里的每个File对象。
  • mergeMap(..., 5):内部会同时订阅最多5个由uploadSingleImage返回的Observable(也就是上传请求),当其中一个请求完成时,会自动订阅下一个文件的上传请求,始终保持并发数不超过5。
  • catchError:保证单个上传失败不会导致整个批量上传流中断,剩余文件会继续处理。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 15:20:21