`title: Fetch Range 请求与断点下载持久化实践``categories: Web 开发/前端/数据管理``keywords: Fetch,Range,部分内容,断点下载,OPFS,分块``description: 使用 HTTP Range 请求实现断点下载与续传,将分块内容写入 OPFS 并在完成后合并,提升大型文件的下载可靠性。`计算块与请求async function fetchChunk(url, start, end) {
const res = await fetch(url, { headers: { Range: `bytes=${start}-${end}` } });
if (!res.ok && res.status !== 206) throw new Error('Range not supported');
return new Uint8Array(await res.arrayBuffer());
}
写入 OPFS(分块)async function writeChunk(name, idx, bytes) {
const root = await navigator.storage.getDirectory();
const handle = await root.getFileHandle(`${name}.part${idx}`, { create: true });
const w = await handle.createWritable();
await w.write(bytes);
await w.close();
}
合并块async function mergeChunks(name, count) {
const root = await navigator.storage.getDirectory();
const out = await root.getFileHandle(name, { create: true });
const w = await out.createWritable();
for (let i = 0; i < count; i++) {
const h = await root.getFileHandle(`${name}.part${i}`);
const file = await h.getFile();
await w.write(await file.arrayBuffer());
}
await w.close();
}
续传策略记录已完成块索引与大小到 IndexedDB;失败重试仅请求缺失块;合并后清理分块。

发表评论 取消回复