概述现代浏览器支持以可读流作为请求体上传。本文提供从文件分块到进度跟踪的端到端示例。能力检测与上传const supportsRS = typeof ReadableStream === 'function'; function streamFromFile(file, size = 1024 * 1024, onProgress) { let o = 0, sent = 0; return new ReadableStream({ async pull(controller) { if (o >= file.size) { controller.close(); return; } const b = file.slice(o, o + size); const ab = await b.arrayBuffer(); const chunk = new Uint8Array(ab); controller.enqueue(chunk); o += size; sent += chunk.length; onProgress && onProgress(sent); } }); } async function upload(url, file) { if (!supportsRS) throw new Error('streams unsupported'); const body = streamFromFile(file, 1024 * 512, s => console.log('sent', s)); const res = await fetch(url, { method: 'POST', body }); if (!res.ok) throw new Error('upload failed'); }

发表评论 取消回复