# 背景与价值
- 通过请求体流式上传,避免一次性组装大数据,配合背压治理提升弱网稳定性。
# 流式请求体
```ts
function makeSource(chunks: Uint8Array[]) {
return new ReadableStream({ 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;
}
```
# 背压控制
```ts
function throttled(chunks: Uint8Array[], n = 4) {
return new ReadableStream({ 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` 支持:分段上传或后端分块接口;避免前端聚合大数据。
# 测试清单
- 大文件与长日志:管线稳定;后端按块接收正确。
发表评论 取消回复