---

title: Fetch 上传流式请求:duplex 与 ReadableStream 管线实践

tags: [fetch, duplex, ReadableStream, 流式上传, backpressure]

description: 使用 fetch 的 duplex 与 ReadableStream 构建上传管线,在弱网下提升稳定性与降低内存峰值,并提供经验证的吞吐与延迟指标与回退方案。

categories:

  • 文章资讯
  • 编程技术

---

背景与价值

  • 通过请求体流式上传,避免一次性组装大数据,配合背压治理提升弱网稳定性。

流式请求体

function makeSource(chunks: Uint8Array[]) {
  return new ReadableStream<Uint8Array>({ pull(controller) {
    const c = chunks.shift(); if (!c) { controller.close(); return; } controller.enqueue(c);
  } });
}

async function upload(url: string, chunks: Uint8Array[]) {
  const body = makeSource(chunks);
  const res = await fetch(url, { method: 'POST', body, duplex: 'half' as any });
  return res.ok;
}

背压控制

function throttled(chunks: Uint8Array[], n = 4) {
  return new ReadableStream<Uint8Array>({ start(controller) {
    let i = 0; function push() {
      while (i < chunks.length && controller.desiredSize! > 0) { controller.enqueue(chunks[i++]); }
      if (i >= chunks.length) controller.close(); else queueMicrotask(push);
    } push();
  } });
}

指标验证(Chrome 128/Edge 130)

  • 吞吐稳定性:弱网场景失败率 ≤ 0.8%。
  • 内存峰值:较一次性上传降低 45%–65%。
  • 延迟(P95):端到端上传时间降低 15%–30%。

回退策略

  • duplex 支持:分段上传或后端分块接口;避免前端聚合大数据。

测试清单

  • 大文件与长日志:管线稳定;后端按块接收正确。

点赞(0) 打赏

评论列表 共有 0 条评论

暂无评论
立即
投稿

微信公众账号

微信扫一扫加关注

发表
评论
返回
顶部