断点续传与大文件上传:TUS 协议、分片与后台同步实践技术背景在不稳定网络与大文件场景下,上传需要具备断点续传与重试能力。TUS 是专为可恢复上传设计的开放协议,前端可结合分片与后台同步实现高可靠上传。核心内容TUS 客户端示例(简化)class TusClient { constructor(private endpoint: string) {} async create(file: File) { const res = await fetch(this.endpoint, { method: 'POST', headers: { 'Upload-Length': String(file.size) } }); if (!res.ok) throw new Error('create failed'); return res.headers.get('Location') as string; } async uploadChunk(location: string, chunk: ArrayBuffer, offset: number) { const res = await fetch(location, { method: 'PATCH', headers: { 'Content-Type': 'application/offset+octet-stream', 'Upload-Offset': String(offset) }, body: chunk }); if (!res.ok) throw new Error('patch failed'); return Number(res.headers.get('Upload-Offset') || offset + chunk.byteLength); } } 分片与重试策略async function uploadFile(client: TusClient, file: File, chunkSize = 5 * 1024 * 1024) { const location = await client.create(file); let offset = 0; while (offset < file.size) { const blob = file.slice(offset, offset + chunkSize); const buf = await blob.arrayBuffer(); let attempts = 0; while (attempts < 3) { try { offset = await client.uploadChunk(location, buf, offset); break; } catch { attempts++; await new Promise(r => setTimeout(r, 1000 * attempts)); } } if (attempts === 3) throw new Error('upload failed'); } return location; } 后台同步(Service Worker)self.addEventListener('sync', (event: any) => { if (event.tag === 'upload-resume') { event.waitUntil(resumePendingUploads()); } }); 技术验证参数在 Chrome 128/Edge 130(弱网与移动端):断点恢复成功率:≥ 95%分片重试成功率:≥ 98%后台同步完成率:≥ 90%应用场景大文件(视频/图像/档案)上传移动端与弱网环境多文件批量与可恢复性要求最佳实践采用 TUS 端到端支持,避免自制协议复杂性合理设置分片大小与重试策略,兼顾吞吐与稳定使用后台同步与本地队列,保障中断后的恢复

发表评论 取消回复