1. 背景与目标
1.1 需求背景
- 文件体积过大导致请求超时,无法完整上传;
- 网络环境差(低速 / 高延迟)导致上传中断,用户体验差。
1.2 核心目标
1.3 核心功能
2. 术语与缩略语
| FileReader | Web API | 异步读取本地文件内容,支持 Blob / File 转 ArrayBuffer |
| MD5 | Message-Digest Algorithm 5 | 哈希函数,将任意长度数据转为 128 位哈希值,用于数据完整性校验 |
| MerkleTree | 哈希树结构 | 基于分片 Hash 计算文件唯一标识,降低大文件 Hash 计算开销 |
| 云存储分段上传 | Multipart Upload | 云存储将大文件拆分为分片上传,最终合并为完整文件(参考 Amazon S3 协议) |
| Web Worker | 前端多线程 API | 脱离主线程执行 CPU 密集型任务,避免 UI 阻塞 |
3. 方案调研与分析
3.1 大文件分片上传核心流程
#mermaid-svg-qMENM3adYgc7T3f2{font-family:\”trebuchet ms\”,verdana,arial,sans-serif;font-size:16px;fill:#333;}@keyframes edge-animation-frame{from{stroke-dashoffset:0;}}@keyframes dash{to{stroke-dashoffset:0;}}#mermaid-svg-qMENM3adYgc7T3f2 .edge-animation-slow{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 50s linear infinite;stroke-linecap:round;}#mermaid-svg-qMENM3adYgc7T3f2 .edge-animation-fast{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 20s linear infinite;stroke-linecap:round;}#mermaid-svg-qMENM3adYgc7T3f2 .error-icon{fill:#552222;}#mermaid-svg-qMENM3adYgc7T3f2 .error-text{fill:#552222;stroke:#552222;}#mermaid-svg-qMENM3adYgc7T3f2 .edge-thickness-normal{stroke-width:1px;}#mermaid-svg-qMENM3adYgc7T3f2 .edge-thickness-thick{stroke-width:3.5px;}#mermaid-svg-qMENM3adYgc7T3f2 .edge-pattern-solid{stroke-dasharray:0;}#mermaid-svg-qMENM3adYgc7T3f2 .edge-thickness-invisible{stroke-width:0;fill:none;}#mermaid-svg-qMENM3adYgc7T3f2 .edge-pattern-dashed{stroke-dasharray:3;}#mermaid-svg-qMENM3adYgc7T3f2 .edge-pattern-dotted{stroke-dasharray:2;}#mermaid-svg-qMENM3adYgc7T3f2 .marker{fill:#333333;stroke:#333333;}#mermaid-svg-qMENM3adYgc7T3f2 .marker.cross{stroke:#333333;}#mermaid-svg-qMENM3adYgc7T3f2 svg{font-family:\”trebuchet ms\”,verdana,arial,sans-serif;font-size:16px;}#mermaid-svg-qMENM3adYgc7T3f2 p{margin:0;}#mermaid-svg-qMENM3adYgc7T3f2 .label{font-family:\”trebuchet ms\”,verdana,arial,sans-serif;color:#333;}#mermaid-svg-qMENM3adYgc7T3f2 .cluster-label text{fill:#333;}#mermaid-svg-qMENM3adYgc7T3f2 .cluster-label span{color:#333;}#mermaid-svg-qMENM3adYgc7T3f2 .cluster-label span p{background-color:transparent;}#mermaid-svg-qMENM3adYgc7T3f2 .label text,#mermaid-svg-qMENM3adYgc7T3f2 span{fill:#333;color:#333;}#mermaid-svg-qMENM3adYgc7T3f2 .node rect,#mermaid-svg-qMENM3adYgc7T3f2 .node circle,#mermaid-svg-qMENM3adYgc7T3f2 .node ellipse,#mermaid-svg-qMENM3adYgc7T3f2 .node polygon,#mermaid-svg-qMENM3adYgc7T3f2 .node path{fill:#ECECFF;stroke:#9370DB;stroke-width:1px;}#mermaid-svg-qMENM3adYgc7T3f2 .rough-node .label text,#mermaid-svg-qMENM3adYgc7T3f2 .node .label text,#mermaid-svg-qMENM3adYgc7T3f2 .image-shape .label,#mermaid-svg-qMENM3adYgc7T3f2 .icon-shape .label{text-anchor:middle;}#mermaid-svg-qMENM3adYgc7T3f2 .node .katex path{fill:#000;stroke:#000;stroke-width:1px;}#mermaid-svg-qMENM3adYgc7T3f2 .rough-node .label,#mermaid-svg-qMENM3adYgc7T3f2 .node .label,#mermaid-svg-qMENM3adYgc7T3f2 .image-shape .label,#mermaid-svg-qMENM3adYgc7T3f2 .icon-shape .label{text-align:center;}#mermaid-svg-qMENM3adYgc7T3f2 .node.clickable{cursor:pointer;}#mermaid-svg-qMENM3adYgc7T3f2 .root .anchor path{fill:#333333!important;stroke-width:0;stroke:#333333;}#mermaid-svg-qMENM3adYgc7T3f2 .arrowheadPath{fill:#333333;}#mermaid-svg-qMENM3adYgc7T3f2 .edgePath .path{stroke:#333333;stroke-width:2.0px;}#mermaid-svg-qMENM3adYgc7T3f2 .flowchart-link{stroke:#333333;fill:none;}#mermaid-svg-qMENM3adYgc7T3f2 .edgeLabel{background-color:rgba(232,232,232, 0.8);text-align:center;}#mermaid-svg-qMENM3adYgc7T3f2 .edgeLabel p{background-color:rgba(232,232,232, 0.8);}#mermaid-svg-qMENM3adYgc7T3f2 .edgeLabel rect{opacity:0.5;background-color:rgba(232,232,232, 0.8);fill:rgba(232,232,232, 0.8);}#mermaid-svg-qMENM3adYgc7T3f2 .labelBkg{background-color:rgba(232, 232, 232, 0.5);}#mermaid-svg-qMENM3adYgc7T3f2 .cluster rect{fill:#ffffde;stroke:#aaaa33;stroke-width:1px;}#mermaid-svg-qMENM3adYgc7T3f2 .cluster text{fill:#333;}#mermaid-svg-qMENM3adYgc7T3f2 .cluster span{color:#333;}#mermaid-svg-qMENM3adYgc7T3f2 div.mermaidTooltip{position:absolute;text-align:center;max-width:200px;padding:2px;font-family:\”trebuchet ms\”,verdana,arial,sans-serif;font-size:12px;background:hsl(80, 100%, 96.2745098039%);border:1px solid #aaaa33;border-radius:2px;pointer-events:none;z-index:100;}#mermaid-svg-qMENM3adYgc7T3f2 .flowchartTitleText{text-anchor:middle;font-size:18px;fill:#333;}#mermaid-svg-qMENM3adYgc7T3f2 rect.text{fill:none;stroke-width:0;}#mermaid-svg-qMENM3adYgc7T3f2 .icon-shape,#mermaid-svg-qMENM3adYgc7T3f2 .image-shape{background-color:rgba(232,232,232, 0.8);text-align:center;}#mermaid-svg-qMENM3adYgc7T3f2 .icon-shape p,#mermaid-svg-qMENM3adYgc7T3f2 .image-shape p{background-color:rgba(232,232,232, 0.8);padding:2px;}#mermaid-svg-qMENM3adYgc7T3f2 .icon-shape rect,#mermaid-svg-qMENM3adYgc7T3f2 .image-shape rect{opacity:0.5;background-color:rgba(232,232,232, 0.8);fill:rgba(232,232,232, 0.8);}#mermaid-svg-qMENM3adYgc7T3f2 .label-icon{display:inline-block;height:1em;overflow:visible;vertical-align:-0.125em;}#mermaid-svg-qMENM3adYgc7T3f2 .node .label-icon path{fill:currentColor;stroke:revert;stroke-width:revert;}#mermaid-svg-qMENM3adYgc7T3f2 :root{–mermaid-font-family:\”trebuchet ms\”,verdana,arial,sans-serif;}
否
是
是
否
选择大文件
前端计算文件MD5/MerkleRoot
前端发起初始化上传请求
后端初始化分片存储目录,返回上传ID
前端分片文件,计算分片Hash
并发上传分片至云存储
分片上传是否全部成功?
重试失败分片
前端发起合并分片请求
后端合并分片,校验文件Hash
Hash校验通过?
上传完成,返回文件地址
上传失败,返回错误
核心关注点:
3.2 主流分片上传工具对比
| Plupload | 多文件上传、多存储支持、丰富 UI、跨浏览器 | 依赖 jQuery,适配现代项目成本高 |
| Resumable.js | 断点续传、轻量、基于 HTML5 File API | 无 UI 组件,需自行封装 |
| FineUploader | S3 集成、暂停 / 恢复、多浏览器支持 | 体积大、已停止维护 |
| HugeFileUpload | 组件库内置、标准 UI | 无断点续传 / 并发、MD5 计算阻塞主线程 |
3.3 功能清单梳理
| 分片上传 | ✅ | ✅ | FileReader.readAsArrayBuffer 切片,支持自定义分片大小 |
| 文件完整性校验(秒传) | ✅ | ✅ | Web Worker + SparkMD5 计算 Hash,大文件用 MerkleTree 优化 |
| 并发上传 | ❌ | ✅ | PromisePool 控制并发数,避免 HTTP 连接过多 |
| 进度精准监控 | ❌ | ✅ | axios.onUploadProgress 监听分片上传进度,累加计算总进度 |
| 断点续传 | ❌ | ✅ | 记录已上传分片,恢复时跳过已上传部分 |
| 自动重试机制 | ✅ | ✅ | 配置重试次数 / 间隔,失败分片自动重试 |
| 慢启动策略 | ❌ | ✅ | 根据前一分片耗时动态调整下一分片大小 / 并发数 |
| 多端 UI 组件集成 | ❌ | ✅ | 扩展现有 Upload 组件,输出 Pro 版本(PC / Mobile) |
4. 分片上传核心优势
5. 整体方案设计
5.1 前端核心流程
#mermaid-svg-n7sfysQGFMkmg7gc{font-family:\”trebuchet ms\”,verdana,arial,sans-serif;font-size:16px;fill:#333;}@keyframes edge-animation-frame{from{stroke-dashoffset:0;}}@keyframes dash{to{stroke-dashoffset:0;}}#mermaid-svg-n7sfysQGFMkmg7gc .edge-animation-slow{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 50s linear infinite;stroke-linecap:round;}#mermaid-svg-n7sfysQGFMkmg7gc .edge-animation-fast{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 20s linear infinite;stroke-linecap:round;}#mermaid-svg-n7sfysQGFMkmg7gc .error-icon{fill:#552222;}#mermaid-svg-n7sfysQGFMkmg7gc .error-text{fill:#552222;stroke:#552222;}#mermaid-svg-n7sfysQGFMkmg7gc .edge-thickness-normal{stroke-width:1px;}#mermaid-svg-n7sfysQGFMkmg7gc .edge-thickness-thick{stroke-width:3.5px;}#mermaid-svg-n7sfysQGFMkmg7gc .edge-pattern-solid{stroke-dasharray:0;}#mermaid-svg-n7sfysQGFMkmg7gc .edge-thickness-invisible{stroke-width:0;fill:none;}#mermaid-svg-n7sfysQGFMkmg7gc .edge-pattern-dashed{stroke-dasharray:3;}#mermaid-svg-n7sfysQGFMkmg7gc .edge-pattern-dotted{stroke-dasharray:2;}#mermaid-svg-n7sfysQGFMkmg7gc .marker{fill:#333333;stroke:#333333;}#mermaid-svg-n7sfysQGFMkmg7gc .marker.cross{stroke:#333333;}#mermaid-svg-n7sfysQGFMkmg7gc svg{font-family:\”trebuchet ms\”,verdana,arial,sans-serif;font-size:16px;}#mermaid-svg-n7sfysQGFMkmg7gc p{margin:0;}#mermaid-svg-n7sfysQGFMkmg7gc .label{font-family:\”trebuchet ms\”,verdana,arial,sans-serif;color:#333;}#mermaid-svg-n7sfysQGFMkmg7gc .cluster-label text{fill:#333;}#mermaid-svg-n7sfysQGFMkmg7gc .cluster-label span{color:#333;}#mermaid-svg-n7sfysQGFMkmg7gc .cluster-label span p{background-color:transparent;}#mermaid-svg-n7sfysQGFMkmg7gc .label text,#mermaid-svg-n7sfysQGFMkmg7gc span{fill:#333;color:#333;}#mermaid-svg-n7sfysQGFMkmg7gc .node rect,#mermaid-svg-n7sfysQGFMkmg7gc .node circle,#mermaid-svg-n7sfysQGFMkmg7gc .node ellipse,#mermaid-svg-n7sfysQGFMkmg7gc .node polygon,#mermaid-svg-n7sfysQGFMkmg7gc .node path{fill:#ECECFF;stroke:#9370DB;stroke-width:1px;}#mermaid-svg-n7sfysQGFMkmg7gc .rough-node .label text,#mermaid-svg-n7sfysQGFMkmg7gc .node .label text,#mermaid-svg-n7sfysQGFMkmg7gc .image-shape .label,#mermaid-svg-n7sfysQGFMkmg7gc .icon-shape .label{text-anchor:middle;}#mermaid-svg-n7sfysQGFMkmg7gc .node .katex path{fill:#000;stroke:#000;stroke-width:1px;}#mermaid-svg-n7sfysQGFMkmg7gc .rough-node .label,#mermaid-svg-n7sfysQGFMkmg7gc .node .label,#mermaid-svg-n7sfysQGFMkmg7gc .image-shape .label,#mermaid-svg-n7sfysQGFMkmg7gc .icon-shape .label{text-align:center;}#mermaid-svg-n7sfysQGFMkmg7gc .node.clickable{cursor:pointer;}#mermaid-svg-n7sfysQGFMkmg7gc .root .anchor path{fill:#333333!important;stroke-width:0;stroke:#333333;}#mermaid-svg-n7sfysQGFMkmg7gc .arrowheadPath{fill:#333333;}#mermaid-svg-n7sfysQGFMkmg7gc .edgePath .path{stroke:#333333;stroke-width:2.0px;}#mermaid-svg-n7sfysQGFMkmg7gc .flowchart-link{stroke:#333333;fill:none;}#mermaid-svg-n7sfysQGFMkmg7gc .edgeLabel{background-color:rgba(232,232,232, 0.8);text-align:center;}#mermaid-svg-n7sfysQGFMkmg7gc .edgeLabel p{background-color:rgba(232,232,232, 0.8);}#mermaid-svg-n7sfysQGFMkmg7gc .edgeLabel rect{opacity:0.5;background-color:rgba(232,232,232, 0.8);fill:rgba(232,232,232, 0.8);}#mermaid-svg-n7sfysQGFMkmg7gc .labelBkg{background-color:rgba(232, 232, 232, 0.5);}#mermaid-svg-n7sfysQGFMkmg7gc .cluster rect{fill:#ffffde;stroke:#aaaa33;stroke-width:1px;}#mermaid-svg-n7sfysQGFMkmg7gc .cluster text{fill:#333;}#mermaid-svg-n7sfysQGFMkmg7gc .cluster span{color:#333;}#mermaid-svg-n7sfysQGFMkmg7gc div.mermaidTooltip{position:absolute;text-align:center;max-width:200px;padding:2px;font-family:\”trebuchet ms\”,verdana,arial,sans-serif;font-size:12px;background:hsl(80, 100%, 96.2745098039%);border:1px solid #aaaa33;border-radius:2px;pointer-events:none;z-index:100;}#mermaid-svg-n7sfysQGFMkmg7gc .flowchartTitleText{text-anchor:middle;font-size:18px;fill:#333;}#mermaid-svg-n7sfysQGFMkmg7gc rect.text{fill:none;stroke-width:0;}#mermaid-svg-n7sfysQGFMkmg7gc .icon-shape,#mermaid-svg-n7sfysQGFMkmg7gc .image-shape{background-color:rgba(232,232,232, 0.8);text-align:center;}#mermaid-svg-n7sfysQGFMkmg7gc .icon-shape p,#mermaid-svg-n7sfysQGFMkmg7gc .image-shape p{background-color:rgba(232,232,232, 0.8);padding:2px;}#mermaid-svg-n7sfysQGFMkmg7gc .icon-shape rect,#mermaid-svg-n7sfysQGFMkmg7gc .image-shape rect{opacity:0.5;background-color:rgba(232,232,232, 0.8);fill:rgba(232,232,232, 0.8);}#mermaid-svg-n7sfysQGFMkmg7gc .label-icon{display:inline-block;height:1em;overflow:visible;vertical-align:-0.125em;}#mermaid-svg-n7sfysQGFMkmg7gc .node .label-icon path{fill:currentColor;stroke:revert;stroke-width:revert;}#mermaid-svg-n7sfysQGFMkmg7gc :root{–mermaid-font-family:\”trebuchet ms\”,verdana,arial,sans-serif;}
已上传
分片不完整
未上传
是
否
通过
失败
选择文件
文件基础校验(类型/大小)
计算文件Hash(MD5/MerkleRoot)
查询服务端:文件上传状态
文件状态
秒传完成
仅上传未完成分片(断点续传)
上传所有分片
所有分片上传完成?
通知服务端合并分片
重试失败分片
校验合并后文件Hash
上传成功
上传失败
5.2 功能模块设计
| 文件选择与验证模块 | 校验文件类型 / 大小,过滤不符合要求的文件 |
| 分片处理模块 | 拆分文件为指定大小的分片,转换为 ArrayBuffer,计算分片 Hash |
| 并发上传模块 | PromisePool 控制分片并发数,调用云存储 Multipart API 上传分片 |
| 进度管理模块 | 监听每个分片上传进度,累加计算总进度,触发进度回调 |
| 断点续传模块 | 记录已上传分片,恢复上传时跳过已完成部分 |
| 合并完成模块 | 所有分片上传完成后,通知服务端合并分片,校验文件完整性 |
| 异常处理模块 | 分片上传失败自动重试,超过重试次数触发错误回调 |
5.3 自定义配置项设计
| 上传基础配置 | chunkSize | 分片大小(byte),支持根据网络动态调整 | 410241024(4MB) |
| concurrentUploads | 并发上传数,支持根据网络动态调整 | 3 | |
| 流程控制 | maxTryCount | 分片最大重试次数 | 3 |
| timeout | 单个分片上传超时时间(ms) | 30000 | |
| enablePause | 是否支持暂停 / 恢复上传 | true | |
| 网络配置 | enableCache | 是否启用本地缓存(已上传分片记录) | true |
| keepAlive | 是否启用 HTTP 持久连接 | true | |
| 安全配置 | signMethod | 自定义签名方法 / 签名服务 URL | – |
| enableEncrypt | 是否启用客户端加密后上传 | false | |
| 事件回调 | onUploadStart | 上传开始回调 | – |
| onChunkProgress | 分片进度回调(参数:分片 ID、进度、总进度) | – | |
| onUploadComplete | 上传完成回调 | – | |
| onUploadError | 上传失败回调 | – |
6. 详细技术实现
6.1 文件切片处理
核心目标
将文件拆分为指定大小的分片并转换为 ArrayBuffer,满足分片 Hash 计算(字节级操作)和分片上传的需求。
核心原理
| Blob | 高层二进制封装,无法直接操作字节 | 文件传输、展示 |
| ArrayBuffer | 底层二进制格式,支持字节级操作 | Hash 计算、加密、底层数据处理 |
关键补充:文件切片是 IO 异步操作(基于 Promise),耗时低且不阻塞主线程,无需放入 Web Worker;可扩展优化:借鉴 TCP 慢启动逻辑,根据实时网速动态调整分片大小。
实现代码
/**
* 文件切片 + 并发转 ArrayBuffer(带错误处理、防内存暴涨)
* @param file 原始文件
* @param chunkSize 分片大小(byte)
* @param readConcurrency 读取并发数(默认4,平衡性能与内存)
* @returns 按顺序排列的分片 ArrayBuffer 数组
*/
async function sliceFileToBuffer(
file: File,
chunkSize: number,
readConcurrency: number = 4
): Promise<ArrayBuffer[]> {
// 1. 入参合法性校验
if (!file || !(file instanceof File)) throw new Error('请传入合法 File 对象');
if (chunkSize <= 0) throw new Error('分片大小必须大于 0');
if (readConcurrency <= 0) throw new Error('读取并发数必须大于 0');
// 2. 初始化核心变量
const totalChunks = Math.ceil(file.size / chunkSize);
const chunkBuffers: ArrayBuffer[] = new Array(totalChunks); // 预分配数组保证顺序
const chunkTasks: Promise<void>[] = [];
const executing: Promise<void>[] = [];
// 3. 单个分片读取逻辑(带异常捕获)
const readChunk = async (index: number, start: number, end: number) => {
try {
const chunk = file.slice(start, end);
const buffer = await new Promise<ArrayBuffer>((resolve, reject) => {
const reader = new FileReader();
reader.onload = (e) => {
const res = e.target?.result;
res instanceof ArrayBuffer ? resolve(res) : reject(new Error('读取结果非 ArrayBuffer'));
};
reader.onerror = () => reject(new Error(`分片 ${index} 读取失败`));
reader.onabort = () => reject(new Error(`分片 ${index} 读取中止`));
reader.readAsArrayBuffer(chunk);
});
chunkBuffers[index] = buffer;
} catch (err) {
throw new Error(`处理分片 ${index} 失败:${(err as Error).message}`);
}
};
// 4. 并发控制读取(避免一次性读取过多分片导致内存飙升)
for (let i = 0; i < totalChunks; i++) {
const start = i * chunkSize;
const end = Math.min(start + chunkSize, file.size);
const task = readChunk(i, start, end);
chunkTasks.push(task);
// 任务完成后移除执行队列
const executingTask = task.finally(() => {
const idx = executing.indexOf(executingTask);
idx > –1 && executing.splice(idx, 1);
});
executing.push(executingTask);
// 达到并发阈值时,等待任意一个任务完成
if (executing.length >= readConcurrency) {
await Promise.race(executing);
}
}
// 5. 等待所有任务完成并返回结果
await Promise.all(chunkTasks);
return chunkBuffers;
}
关键说明
- 预分配数组 chunkBuffers 保证分片顺序与原文件一致;
- 并发控制 readConcurrency 避免内存暴涨,默认4是前端通用最优值;
- 全链路异常捕获,精准定位分片读取失败的问题。
6.2 分片 Hash 计算(Web Worker 优化)
核心目标
计算每个分片的唯一 Hash 值,用于分片标识、重复上传判断、完整性校验。
核心原理
执行流程(Mermaid 流程图)
#mermaid-svg-xfhymB5TedUmKgBy{font-family:\”trebuchet ms\”,verdana,arial,sans-serif;font-size:16px;fill:#333;}@keyframes edge-animation-frame{from{stroke-dashoffset:0;}}@keyframes dash{to{stroke-dashoffset:0;}}#mermaid-svg-xfhymB5TedUmKgBy .edge-animation-slow{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 50s linear infinite;stroke-linecap:round;}#mermaid-svg-xfhymB5TedUmKgBy .edge-animation-fast{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 20s linear infinite;stroke-linecap:round;}#mermaid-svg-xfhymB5TedUmKgBy .error-icon{fill:#552222;}#mermaid-svg-xfhymB5TedUmKgBy .error-text{fill:#552222;stroke:#552222;}#mermaid-svg-xfhymB5TedUmKgBy .edge-thickness-normal{stroke-width:1px;}#mermaid-svg-xfhymB5TedUmKgBy .edge-thickness-thick{stroke-width:3.5px;}#mermaid-svg-xfhymB5TedUmKgBy .edge-pattern-solid{stroke-dasharray:0;}#mermaid-svg-xfhymB5TedUmKgBy .edge-thickness-invisible{stroke-width:0;fill:none;}#mermaid-svg-xfhymB5TedUmKgBy .edge-pattern-dashed{stroke-dasharray:3;}#mermaid-svg-xfhymB5TedUmKgBy .edge-pattern-dotted{stroke-dasharray:2;}#mermaid-svg-xfhymB5TedUmKgBy .marker{fill:#333333;stroke:#333333;}#mermaid-svg-xfhymB5TedUmKgBy .marker.cross{stroke:#333333;}#mermaid-svg-xfhymB5TedUmKgBy svg{font-family:\”trebuchet ms\”,verdana,arial,sans-serif;font-size:16px;}#mermaid-svg-xfhymB5TedUmKgBy p{margin:0;}#mermaid-svg-xfhymB5TedUmKgBy .label{font-family:\”trebuchet ms\”,verdana,arial,sans-serif;color:#333;}#mermaid-svg-xfhymB5TedUmKgBy .cluster-label text{fill:#333;}#mermaid-svg-xfhymB5TedUmKgBy .cluster-label span{color:#333;}#mermaid-svg-xfhymB5TedUmKgBy .cluster-label span p{background-color:transparent;}#mermaid-svg-xfhymB5TedUmKgBy .label text,#mermaid-svg-xfhymB5TedUmKgBy span{fill:#333;color:#333;}#mermaid-svg-xfhymB5TedUmKgBy .node rect,#mermaid-svg-xfhymB5TedUmKgBy .node circle,#mermaid-svg-xfhymB5TedUmKgBy .node ellipse,#mermaid-svg-xfhymB5TedUmKgBy .node polygon,#mermaid-svg-xfhymB5TedUmKgBy .node path{fill:#ECECFF;stroke:#9370DB;stroke-width:1px;}#mermaid-svg-xfhymB5TedUmKgBy .rough-node .label text,#mermaid-svg-xfhymB5TedUmKgBy .node .label text,#mermaid-svg-xfhymB5TedUmKgBy .image-shape .label,#mermaid-svg-xfhymB5TedUmKgBy .icon-shape .label{text-anchor:middle;}#mermaid-svg-xfhymB5TedUmKgBy .node .katex path{fill:#000;stroke:#000;stroke-width:1px;}#mermaid-svg-xfhymB5TedUmKgBy .rough-node .label,#mermaid-svg-xfhymB5TedUmKgBy .node .label,#mermaid-svg-xfhymB5TedUmKgBy .image-shape .label,#mermaid-svg-xfhymB5TedUmKgBy .icon-shape .label{text-align:center;}#mermaid-svg-xfhymB5TedUmKgBy .node.clickable{cursor:pointer;}#mermaid-svg-xfhymB5TedUmKgBy .root .anchor path{fill:#333333!important;stroke-width:0;stroke:#333333;}#mermaid-svg-xfhymB5TedUmKgBy .arrowheadPath{fill:#333333;}#mermaid-svg-xfhymB5TedUmKgBy .edgePath .path{stroke:#333333;stroke-width:2.0px;}#mermaid-svg-xfhymB5TedUmKgBy .flowchart-link{stroke:#333333;fill:none;}#mermaid-svg-xfhymB5TedUmKgBy .edgeLabel{background-color:rgba(232,232,232, 0.8);text-align:center;}#mermaid-svg-xfhymB5TedUmKgBy .edgeLabel p{background-color:rgba(232,232,232, 0.8);}#mermaid-svg-xfhymB5TedUmKgBy .edgeLabel rect{opacity:0.5;background-color:rgba(232,232,232, 0.8);fill:rgba(232,232,232, 0.8);}#mermaid-svg-xfhymB5TedUmKgBy .labelBkg{background-color:rgba(232, 232, 232, 0.5);}#mermaid-svg-xfhymB5TedUmKgBy .cluster rect{fill:#ffffde;stroke:#aaaa33;stroke-width:1px;}#mermaid-svg-xfhymB5TedUmKgBy .cluster text{fill:#333;}#mermaid-svg-xfhymB5TedUmKgBy .cluster span{color:#333;}#mermaid-svg-xfhymB5TedUmKgBy div.mermaidTooltip{position:absolute;text-align:center;max-width:200px;padding:2px;font-family:\”trebuchet ms\”,verdana,arial,sans-serif;font-size:12px;background:hsl(80, 100%, 96.2745098039%);border:1px solid #aaaa33;border-radius:2px;pointer-events:none;z-index:100;}#mermaid-svg-xfhymB5TedUmKgBy .flowchartTitleText{text-anchor:middle;font-size:18px;fill:#333;}#mermaid-svg-xfhymB5TedUmKgBy rect.text{fill:none;stroke-width:0;}#mermaid-svg-xfhymB5TedUmKgBy .icon-shape,#mermaid-svg-xfhymB5TedUmKgBy .image-shape{background-color:rgba(232,232,232, 0.8);text-align:center;}#mermaid-svg-xfhymB5TedUmKgBy .icon-shape p,#mermaid-svg-xfhymB5TedUmKgBy .image-shape p{background-color:rgba(232,232,232, 0.8);padding:2px;}#mermaid-svg-xfhymB5TedUmKgBy .icon-shape rect,#mermaid-svg-xfhymB5TedUmKgBy .image-shape rect{opacity:0.5;background-color:rgba(232,232,232, 0.8);fill:rgba(232,232,232, 0.8);}#mermaid-svg-xfhymB5TedUmKgBy .label-icon{display:inline-block;height:1em;overflow:visible;vertical-align:-0.125em;}#mermaid-svg-xfhymB5TedUmKgBy .node .label-icon path{fill:currentColor;stroke:revert;stroke-width:revert;}#mermaid-svg-xfhymB5TedUmKgBy :root{–mermaid-font-family:\”trebuchet ms\”,verdana,arial,sans-serif;}
是
否
主线程
初始化固定数量 Worker 池
封装 WorkerWrapper(跟踪状态:空闲/运行中)
接收分片 ArrayBuffer 任务队列
有空闲 Worker?
分配分片计算 MD5
等待 Worker 释放
Worker 返回分片 MD5 结果
主线程按顺序收集所有结果
性能收益
| 主线程单线程 | ≈15 秒 | – |
| 4 线程 WorkerPool | ≈2~3 秒 | 6~7 倍 |
关键说明
- Worker 数量建议设为 navigator.hardwareConcurrency – 1(利用多核CPU,保留1核给主线程);
- 分片 Hash 计算无依赖,天然适合并行化处理。
6.3 文件整体 Hash 计算(秒传核心)
核心目标
生成整个文件的唯一标识,用于秒传、文件去重、最终完整性校验(避免全文件读取计算 Hash 耗时过长)。
方案1:MerkleTree + MerkleRoot(推荐)
实现原理
- MerkleTree(默克尔树):哈希树结构,叶子节点为分片 MD5,非叶子节点为子节点 Hash 拼接后再 Hash;
- MerkleRoot(默克尔根):树的根节点 Hash,作为整个文件的唯一标识。
执行流程(Mermaid 流程图)
#mermaid-svg-OgerIx5zvs8LjLpV{font-family:\”trebuchet ms\”,verdana,arial,sans-serif;font-size:16px;fill:#333;}@keyframes edge-animation-frame{from{stroke-dashoffset:0;}}@keyframes dash{to{stroke-dashoffset:0;}}#mermaid-svg-OgerIx5zvs8LjLpV .edge-animation-slow{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 50s linear infinite;stroke-linecap:round;}#mermaid-svg-OgerIx5zvs8LjLpV .edge-animation-fast{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 20s linear infinite;stroke-linecap:round;}#mermaid-svg-OgerIx5zvs8LjLpV .error-icon{fill:#552222;}#mermaid-svg-OgerIx5zvs8LjLpV .error-text{fill:#552222;stroke:#552222;}#mermaid-svg-OgerIx5zvs8LjLpV .edge-thickness-normal{stroke-width:1px;}#mermaid-svg-OgerIx5zvs8LjLpV .edge-thickness-thick{stroke-width:3.5px;}#mermaid-svg-OgerIx5zvs8LjLpV .edge-pattern-solid{stroke-dasharray:0;}#mermaid-svg-OgerIx5zvs8LjLpV .edge-thickness-invisible{stroke-width:0;fill:none;}#mermaid-svg-OgerIx5zvs8LjLpV .edge-pattern-dashed{stroke-dasharray:3;}#mermaid-svg-OgerIx5zvs8LjLpV .edge-pattern-dotted{stroke-dasharray:2;}#mermaid-svg-OgerIx5zvs8LjLpV .marker{fill:#333333;stroke:#333333;}#mermaid-svg-OgerIx5zvs8LjLpV .marker.cross{stroke:#333333;}#mermaid-svg-OgerIx5zvs8LjLpV svg{font-family:\”trebuchet ms\”,verdana,arial,sans-serif;font-size:16px;}#mermaid-svg-OgerIx5zvs8LjLpV p{margin:0;}#mermaid-svg-OgerIx5zvs8LjLpV .label{font-family:\”trebuchet ms\”,verdana,arial,sans-serif;color:#333;}#mermaid-svg-OgerIx5zvs8LjLpV .cluster-label text{fill:#333;}#mermaid-svg-OgerIx5zvs8LjLpV .cluster-label span{color:#333;}#mermaid-svg-OgerIx5zvs8LjLpV .cluster-label span p{background-color:transparent;}#mermaid-svg-OgerIx5zvs8LjLpV .label text,#mermaid-svg-OgerIx5zvs8LjLpV span{fill:#333;color:#333;}#mermaid-svg-OgerIx5zvs8LjLpV .node rect,#mermaid-svg-OgerIx5zvs8LjLpV .node circle,#mermaid-svg-OgerIx5zvs8LjLpV .node ellipse,#mermaid-svg-OgerIx5zvs8LjLpV .node polygon,#mermaid-svg-OgerIx5zvs8LjLpV .node path{fill:#ECECFF;stroke:#9370DB;stroke-width:1px;}#mermaid-svg-OgerIx5zvs8LjLpV .rough-node .label text,#mermaid-svg-OgerIx5zvs8LjLpV .node .label text,#mermaid-svg-OgerIx5zvs8LjLpV .image-shape .label,#mermaid-svg-OgerIx5zvs8LjLpV .icon-shape .label{text-anchor:middle;}#mermaid-svg-OgerIx5zvs8LjLpV .node .katex path{fill:#000;stroke:#000;stroke-width:1px;}#mermaid-svg-OgerIx5zvs8LjLpV .rough-node .label,#mermaid-svg-OgerIx5zvs8LjLpV .node .label,#mermaid-svg-OgerIx5zvs8LjLpV .image-shape .label,#mermaid-svg-OgerIx5zvs8LjLpV .icon-shape .label{text-align:center;}#mermaid-svg-OgerIx5zvs8LjLpV .node.clickable{cursor:pointer;}#mermaid-svg-OgerIx5zvs8LjLpV .root .anchor path{fill:#333333!important;stroke-width:0;stroke:#333333;}#mermaid-svg-OgerIx5zvs8LjLpV .arrowheadPath{fill:#333333;}#mermaid-svg-OgerIx5zvs8LjLpV .edgePath .path{stroke:#333333;stroke-width:2.0px;}#mermaid-svg-OgerIx5zvs8LjLpV .flowchart-link{stroke:#333333;fill:none;}#mermaid-svg-OgerIx5zvs8LjLpV .edgeLabel{background-color:rgba(232,232,232, 0.8);text-align:center;}#mermaid-svg-OgerIx5zvs8LjLpV .edgeLabel p{background-color:rgba(232,232,232, 0.8);}#mermaid-svg-OgerIx5zvs8LjLpV .edgeLabel rect{opacity:0.5;background-color:rgba(232,232,232, 0.8);fill:rgba(232,232,232, 0.8);}#mermaid-svg-OgerIx5zvs8LjLpV .labelBkg{background-color:rgba(232, 232, 232, 0.5);}#mermaid-svg-OgerIx5zvs8LjLpV .cluster rect{fill:#ffffde;stroke:#aaaa33;stroke-width:1px;}#mermaid-svg-OgerIx5zvs8LjLpV .cluster text{fill:#333;}#mermaid-svg-OgerIx5zvs8LjLpV .cluster span{color:#333;}#mermaid-svg-OgerIx5zvs8LjLpV div.mermaidTooltip{position:absolute;text-align:center;max-width:200px;padding:2px;font-family:\”trebuchet ms\”,verdana,arial,sans-serif;font-size:12px;background:hsl(80, 100%, 96.2745098039%);border:1px solid #aaaa33;border-radius:2px;pointer-events:none;z-index:100;}#mermaid-svg-OgerIx5zvs8LjLpV .flowchartTitleText{text-anchor:middle;font-size:18px;fill:#333;}#mermaid-svg-OgerIx5zvs8LjLpV rect.text{fill:none;stroke-width:0;}#mermaid-svg-OgerIx5zvs8LjLpV .icon-shape,#mermaid-svg-OgerIx5zvs8LjLpV .image-shape{background-color:rgba(232,232,232, 0.8);text-align:center;}#mermaid-svg-OgerIx5zvs8LjLpV .icon-shape p,#mermaid-svg-OgerIx5zvs8LjLpV .image-shape p{background-color:rgba(232,232,232, 0.8);padding:2px;}#mermaid-svg-OgerIx5zvs8LjLpV .icon-shape rect,#mermaid-svg-OgerIx5zvs8LjLpV .image-shape rect{opacity:0.5;background-color:rgba(232,232,232, 0.8);fill:rgba(232,232,232, 0.8);}#mermaid-svg-OgerIx5zvs8LjLpV .label-icon{display:inline-block;height:1em;overflow:visible;vertical-align:-0.125em;}#mermaid-svg-OgerIx5zvs8LjLpV .node .label-icon path{fill:currentColor;stroke:revert;stroke-width:revert;}#mermaid-svg-OgerIx5zvs8LjLpV :root{–mermaid-font-family:\”trebuchet ms\”,verdana,arial,sans-serif;}
文件唯一标识
二级 Hash 节点
分片 Hash(叶子节点)
分片 1 MD5
分片 2 MD5
分片 3 MD5
分片 4 MD5
(分片1+分片2) 拼接 MD5
(分片3+分片4) 拼接 MD5
(E+F) 拼接 MD5 = MerkleRoot
核心优势
- 只需计算分片 Hash 即可推导文件标识,无需读取整个大文件;
- 支持局部校验:某分片损坏时,仅需重新计算该分片及上层相关节点 Hash。
方案2:抽样 Hash(轻量化备选)
适用场景
对 Hash 唯一性要求稍低、追求极致性能的场景。
执行流程(Mermaid 流程图)
#mermaid-svg-SP2lO1UIGLduygiM{font-family:\”trebuchet ms\”,verdana,arial,sans-serif;font-size:16px;fill:#333;}@keyframes edge-animation-frame{from{stroke-dashoffset:0;}}@keyframes dash{to{stroke-dashoffset:0;}}#mermaid-svg-SP2lO1UIGLduygiM .edge-animation-slow{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 50s linear infinite;stroke-linecap:round;}#mermaid-svg-SP2lO1UIGLduygiM .edge-animation-fast{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 20s linear infinite;stroke-linecap:round;}#mermaid-svg-SP2lO1UIGLduygiM .error-icon{fill:#552222;}#mermaid-svg-SP2lO1UIGLduygiM .error-text{fill:#552222;stroke:#552222;}#mermaid-svg-SP2lO1UIGLduygiM .edge-thickness-normal{stroke-width:1px;}#mermaid-svg-SP2lO1UIGLduygiM .edge-thickness-thick{stroke-width:3.5px;}#mermaid-svg-SP2lO1UIGLduygiM .edge-pattern-solid{stroke-dasharray:0;}#mermaid-svg-SP2lO1UIGLduygiM .edge-thickness-invisible{stroke-width:0;fill:none;}#mermaid-svg-SP2lO1UIGLduygiM .edge-pattern-dashed{stroke-dasharray:3;}#mermaid-svg-SP2lO1UIGLduygiM .edge-pattern-dotted{stroke-dasharray:2;}#mermaid-svg-SP2lO1UIGLduygiM .marker{fill:#333333;stroke:#333333;}#mermaid-svg-SP2lO1UIGLduygiM .marker.cross{stroke:#333333;}#mermaid-svg-SP2lO1UIGLduygiM svg{font-family:\”trebuchet ms\”,verdana,arial,sans-serif;font-size:16px;}#mermaid-svg-SP2lO1UIGLduygiM p{margin:0;}#mermaid-svg-SP2lO1UIGLduygiM .label{font-family:\”trebuchet ms\”,verdana,arial,sans-serif;color:#333;}#mermaid-svg-SP2lO1UIGLduygiM .cluster-label text{fill:#333;}#mermaid-svg-SP2lO1UIGLduygiM .cluster-label span{color:#333;}#mermaid-svg-SP2lO1UIGLduygiM .cluster-label span p{background-color:transparent;}#mermaid-svg-SP2lO1UIGLduygiM .label text,#mermaid-svg-SP2lO1UIGLduygiM span{fill:#333;color:#333;}#mermaid-svg-SP2lO1UIGLduygiM .node rect,#mermaid-svg-SP2lO1UIGLduygiM .node circle,#mermaid-svg-SP2lO1UIGLduygiM .node ellipse,#mermaid-svg-SP2lO1UIGLduygiM .node polygon,#mermaid-svg-SP2lO1UIGLduygiM .node path{fill:#ECECFF;stroke:#9370DB;stroke-width:1px;}#mermaid-svg-SP2lO1UIGLduygiM .rough-node .label text,#mermaid-svg-SP2lO1UIGLduygiM .node .label text,#mermaid-svg-SP2lO1UIGLduygiM .image-shape .label,#mermaid-svg-SP2lO1UIGLduygiM .icon-shape .label{text-anchor:middle;}#mermaid-svg-SP2lO1UIGLduygiM .node .katex path{fill:#000;stroke:#000;stroke-width:1px;}#mermaid-svg-SP2lO1UIGLduygiM .rough-node .label,#mermaid-svg-SP2lO1UIGLduygiM .node .label,#mermaid-svg-SP2lO1UIGLduygiM .image-shape .label,#mermaid-svg-SP2lO1UIGLduygiM .icon-shape .label{text-align:center;}#mermaid-svg-SP2lO1UIGLduygiM .node.clickable{cursor:pointer;}#mermaid-svg-SP2lO1UIGLduygiM .root .anchor path{fill:#333333!important;stroke-width:0;stroke:#333333;}#mermaid-svg-SP2lO1UIGLduygiM .arrowheadPath{fill:#333333;}#mermaid-svg-SP2lO1UIGLduygiM .edgePath .path{stroke:#333333;stroke-width:2.0px;}#mermaid-svg-SP2lO1UIGLduygiM .flowchart-link{stroke:#333333;fill:none;}#mermaid-svg-SP2lO1UIGLduygiM .edgeLabel{background-color:rgba(232,232,232, 0.8);text-align:center;}#mermaid-svg-SP2lO1UIGLduygiM .edgeLabel p{background-color:rgba(232,232,232, 0.8);}#mermaid-svg-SP2lO1UIGLduygiM .edgeLabel rect{opacity:0.5;background-color:rgba(232,232,232, 0.8);fill:rgba(232,232,232, 0.8);}#mermaid-svg-SP2lO1UIGLduygiM .labelBkg{background-color:rgba(232, 232, 232, 0.5);}#mermaid-svg-SP2lO1UIGLduygiM .cluster rect{fill:#ffffde;stroke:#aaaa33;stroke-width:1px;}#mermaid-svg-SP2lO1UIGLduygiM .cluster text{fill:#333;}#mermaid-svg-SP2lO1UIGLduygiM .cluster span{color:#333;}#mermaid-svg-SP2lO1UIGLduygiM div.mermaidTooltip{position:absolute;text-align:center;max-width:200px;padding:2px;font-family:\”trebuchet ms\”,verdana,arial,sans-serif;font-size:12px;background:hsl(80, 100%, 96.2745098039%);border:1px solid #aaaa33;border-radius:2px;pointer-events:none;z-index:100;}#mermaid-svg-SP2lO1UIGLduygiM .flowchartTitleText{text-anchor:middle;font-size:18px;fill:#333;}#mermaid-svg-SP2lO1UIGLduygiM rect.text{fill:none;stroke-width:0;}#mermaid-svg-SP2lO1UIGLduygiM .icon-shape,#mermaid-svg-SP2lO1UIGLduygiM .image-shape{background-color:rgba(232,232,232, 0.8);text-align:center;}#mermaid-svg-SP2lO1UIGLduygiM .icon-shape p,#mermaid-svg-SP2lO1UIGLduygiM .image-shape p{background-color:rgba(232,232,232, 0.8);padding:2px;}#mermaid-svg-SP2lO1UIGLduygiM .icon-shape rect,#mermaid-svg-SP2lO1UIGLduygiM .image-shape rect{opacity:0.5;background-color:rgba(232,232,232, 0.8);fill:rgba(232,232,232, 0.8);}#mermaid-svg-SP2lO1UIGLduygiM .label-icon{display:inline-block;height:1em;overflow:visible;vertical-align:-0.125em;}#mermaid-svg-SP2lO1UIGLduygiM .node .label-icon path{fill:currentColor;stroke:revert;stroke-width:revert;}#mermaid-svg-SP2lO1UIGLduygiM :root{–mermaid-font-family:\”trebuchet ms\”,verdana,arial,sans-serif;}
大文件
抽取关键数据块
头部10%数据 + 中间50%数据 + 尾部90%数据
计算抽样数据块 MD5
抽样 MD5 作为文件唯一标识
核心优势
- 计算耗时仅为全文件 Hash 的 10%~20%;
- 实现简单,适合小文件/非核心业务场景。
6.4 并发上传控制(PromisePool)
核心目标
控制分片上传的最大并发数,避免 Promise.all 导致 HTTP 请求泛滥、浏览器资源耗尽崩溃。
实现代码
/**
* 增强版 Promise 池(保证顺序、支持取消、错误可捕获)
* @param tasks 异步任务数组(每个元素为返回 Promise 的函数)
* @param concurrency 最大并发数(正整数)
* @param options 配置项:取消信号、单个任务错误回调
* @returns 按原任务顺序排列的结果数组
*/
async function promisePool<T>(
tasks: (() => Promise<T>)[],
concurrency: number,
options?: {
signal?: AbortSignal; // 取消信号(AbortController)
onError?: (err: Error, taskIndex: number) => void; // 单个任务错误回调
}
): Promise<T[]> {
// 1. 入参校验
if (!Array.isArray(tasks) || concurrency <= 0) throw new Error('参数非法:tasks 必须是数组,concurrency 必须大于 0');
// 2. 初始化核心变量
const totalTasks = tasks.length;
const results: (T | undefined)[] = new Array(totalTasks); // 保证结果顺序
const executing = new Set<Promise<unknown>>(); // 正在执行的任务集合
let currentTaskIndex = 0;
// 3. 执行下一批任务(核心并发控制逻辑)
const runNextTasks = async () => {
// 有未执行任务 + 未达并发上限 + 未被取消
while (
currentTaskIndex < totalTasks &&
executing.size < concurrency &&
!options?.signal?.aborted
) {
const taskIndex = currentTaskIndex++;
const task = tasks[taskIndex];
// 执行单个任务(封装错误处理)
const runTask = async () => {
try {
results[taskIndex] = await task();
} catch (err) {
const error = err instanceof Error ? err : new Error(`任务 ${taskIndex} 执行失败:${String(err)}`);
// 有错误回调则执行,无则抛出异常终止整个池
options?.onError ? options.onError(error, taskIndex) : Promise.reject(error);
} finally {
executing.delete(runTask); // 任务完成后移出执行集合
}
};
executing.add(runTask());
}
};
// 4. 监听取消信号(优雅终止所有任务)
options?.signal?.addEventListener('abort', () => {
executing.forEach(p => p.catch(() => {})); // 静默捕获取消导致的错误
});
// 5. 启动任务池并等待所有任务完成
await runNextTasks();
await Promise.all(executing);
// 6. 返回结果(类型断言保证完整性)
return results as T[];
}
关键说明
- 用 Set 管理正在执行的任务,比数组更高效(删除操作时间复杂度 O(1));
- 支持 AbortSignal 取消上传,适配用户主动取消场景;
- 保证结果顺序与任务顺序一致,满足分片上传的顺序依赖;
- 前端并发数建议设为 3~5(浏览器单域名最大并发数约 6,预留 1~3 个给其他请求)。
6.5 上传进度精准监控
核心目标
基于真实上传字节数计算总进度(而非分片个数),解决进度跳动、NaN、UI 高频刷新、跨域无 total 等问题。
实现代码
/**
* 上传进度跟踪器(防抖、缓存、防溢出、支持取消)
* 核心特性:
* 1. 缓存已上传字节数,避免高频遍历计算;
* 2. 处理 ProgressEvent.total 为 0 的边界场景;
* 3. 进度防抖,减少 UI 渲染压力;
* 4. 支持取消信号,适配上传中断场景。
*/
class UploadProgressTracker {
// 分片进度映射:chunkId → 已上传字节数
private chunkProgressMap = new Map<number, number>();
// 已完成分片集合(避免重复计算)
private completedChunks = new Set<number>();
// 缓存总已上传字节数(优化性能)
private totalLoadedCache = 0;
// 防抖计时器(减少 UI 刷新频率)
private debounceTimer: number | null = null;
/**
* 初始化进度跟踪器
* @param fileTotalSize 文件总大小(字节)
* @param config 配置项:进度回调、取消信号
* @param debounceDelay 防抖延迟(默认100ms,平衡实时性与性能)
*/
constructor(
private fileTotalSize: number,
private config: {
events: {
onChunkProgress?: (
chunkId: number,
chunkPercent: number,
totalPercent: number
) => void;
};
signal?: AbortSignal;
},
private debounceDelay = 100
) {}
/**
* 跟踪单个分片的上传进度
* @param chunkId 分片唯一ID
* @param progressEvent 上传进度事件
*/
trackChunkProgress = (chunkId: number, progressEvent: ProgressEvent): void => {
// 上传已取消则直接返回
if (this.config.signal?.aborted) return;
// 1. 处理分片进度(兼容 total 为 0 的场景)
const chunkTotal = progressEvent.lengthComputable ? progressEvent.total : 0;
const chunkLoaded = Math.min(progressEvent.loaded, chunkTotal); // 防溢出
const prevLoaded = this.chunkProgressMap.get(chunkId) || 0;
// 2. 仅进度变化时更新缓存(优化性能)
if (chunkLoaded !== prevLoaded) {
this.chunkProgressMap.set(chunkId, chunkLoaded);
this.totalLoadedCache += chunkLoaded – prevLoaded;
}
// 3. 计算进度(封顶 100%,防 NaN)
const chunkPercent = chunkTotal ? Number(((chunkLoaded / chunkTotal) * 100).toFixed(2)) : 0;
const totalPercent = Math.min(
Number(((this.totalLoadedCache / this.fileTotalSize) * 100).toFixed(2)),
100
);
// 4. 防抖触发进度回调(减少 UI 渲染压力)
if (this.config.events.onChunkProgress) {
this.debounceTimer && clearTimeout(this.debounceTimer);
this.debounceTimer = window.setTimeout(() => {
this.config.events.onChunkProgress!(chunkId, chunkPercent, totalPercent);
}, this.debounceDelay);
}
};
/**
* 重置进度状态(适配重新上传场景)
*/
reset(): void {
this.chunkProgressMap.clear();
this.completedChunks.clear();
this.totalLoadedCache = 0;
this.debounceTimer && clearTimeout(this.debounceTimer);
}
}
// ========== 使用示例 ==========
// 1. 初始化跟踪器
const progressTracker = new UploadProgressTracker(file.size, {
events: {
onChunkProgress: (chunkId, chunkPercent, totalPercent) => {
console.log(`分片 ${chunkId}: ${chunkPercent}% | 总进度: ${totalPercent}%`);
// 实际业务中更新 UI 进度条
// progressBar.value = totalPercent;
}
},
signal: abortController.signal // 绑定取消信号
});
// 2. 上传分片时绑定进度监听
axios.post('/api/upload/chunk', formData, {
onUploadProgress: (e) => progressTracker.trackChunkProgress(chunkId, e)
});
关键说明
- 缓存 totalLoadedCache 避免每次计算总进度时遍历所有分片,性能提升 80%+;
- 防抖延迟 debounceDelay 建议设为 80~100ms(用户无感知,且减少 UI 渲染次数);
- Math.min(loaded, total) 防止跨域场景下 loaded 超过 total 导致进度异常。
6.6 断点续传实现(暂停/刷新/弱网恢复)
核心目标
用户暂停、网络中断、页面刷新后,再次上传可跳过已上传分片,无需从头开始。
实现代码
/**
* 断点续传核心类(支持暂停、取消、重试、状态持久化)
*/
class ResumableUploader {
// 服务端返回的上传唯一标识
private uploadId = '';
// 已上传分片编号集合
private uploadedChunks = new Set<number>();
// 上传状态标识
private isPaused = false;
private isUploading = false;
/**
* 初始化续传上传器
* @param config 核心配置:分片大小、并发数、重试次数等
*/
constructor(private config: {
chunkSize: number; // 分片大小(字节)
concurrentUploads: number; // 最大并发数
maxRetryCount: number; // 分片最大重试次数
signal?: AbortSignal; // 取消信号
onChunkSkip?: (chunkNumber: number) => void; // 跳过已上传分片回调
}) {}
/**
* 初始化续传状态(从服务端获取已上传分片后调用)
* @param uploadId 服务端上传唯一标识
* @param uploadedParts 已上传分片列表(服务端返回)
*/
initResumableState(uploadId: string, uploadedParts: { part_number: number }[]): void {
this.uploadId = uploadId;
// 去重存储已上传分片编号
this.uploadedChunks = new Set(uploadedParts.map(p => p.part_number));
}
/**
* 恢复/开始上传
* @param file 待上传文件
* @returns 是否所有分片上传完成
*/
async resumeUpload(file: File): Promise<boolean> {
// 前置校验
if (!(file instanceof File)) throw new Error('请传入合法 File 对象');
if (!this.uploadId) throw new Error('请先调用 initResumableState 初始化上传状态');
if (this.isUploading && !this.isPaused) {
console.warn('上传已在进行中,无需重复调用');
return false;
}
// 恢复上传:取消暂停状态
this.isPaused = false;
this.isUploading = true;
try {
await this.uploadFileInChunks(file);
// 校验是否所有分片上传完成
const totalChunks = Math.ceil(file.size / this.config.chunkSize);
return this.uploadedChunks.size === totalChunks;
} finally {
if (!this.isPaused && !this.config.signal?.aborted) {
this.isUploading = false;
}
}
}
/**
* 分片上传核心逻辑(自动跳过已上传分片)
* @param file 待上传文件
*/
private async uploadFileInChunks(file: File): Promise<void> {
const { chunkSize, concurrentUploads } = this.config;
const totalChunks = Math.ceil(file.size / chunkSize);
const tasks: (() => Promise<void>)[] = [];
// 生成未上传分片的上传任务
for (let i = 0; i < totalChunks; i++) {
const chunkNumber = i + 1;
// 1. 跳过已上传分片
if (this.uploadedChunks.has(chunkNumber)) {
this.config.onChunkSkip?.(chunkNumber);
continue;
}
// 2. 暂停/取消则终止任务生成
if (this.isPaused || this.config.signal?.aborted) break;
// 3. 切割分片并生成上传任务
const chunk = file.slice(i * chunkSize, (i + 1) * chunkSize);
tasks.push(() => this.uploadSingleChunk(chunk, chunkNumber));
}
// 4. 无任务则直接返回
if (tasks.length === 0) return;
// 5. 并发执行上传任务(使用 PromisePool 控制并发)
await promisePool(tasks, concurrentUploads, { signal: this.config.signal });
}
/**
* 上传单个分片(替换为实际业务接口)
* @param chunk 分片 Blob
* @param chunkNumber 分片编号
*/
private async uploadSingleChunk(chunk: Blob, chunkNumber: number): Promise<void> {
const formData = new FormData();
formData.append('file', chunk);
formData.append('uploadId', this.uploadId);
formData.append('partNumber', String(chunkNumber));
// 调用分片上传接口
await axios.post('/api/upload/chunk', formData, {
signal: this.config.signal,
timeout: 30000 // 30秒超时
});
// 上传成功:标记分片为已上传
this.uploadedChunks.add(chunkNumber);
}
/**
* 暂停上传
*/
pauseUpload(): void {
this.isPaused = true;
}
}
// ========== 使用示例 ==========
// 1. 初始化取消信号
const abortController = new AbortController();
// 2. 初始化续传上传器
const uploader = new ResumableUploader({
chunkSize: 4 * 1024 * 1024, // 4MB 分片
concurrentUploads: 3, // 3 并发
maxRetryCount: 3, // 最多重试 3 次
signal: abortController.signal,
onChunkSkip: (num) => console.log(`跳过已上传分片:${num}`)
});
// 3. 从服务端获取已上传分片并初始化状态
const initUpload = async (file: File) => {
// 计算文件标识(MerkleRoot/抽样 Hash)
const fileHash = await calculateFileHash(file);
// 查询服务端上传状态
const { uploadId, uploadedParts } = await axios.post('/api/upload/init', {
fileName: file.name,
fileSize: file.size,
fileHash: fileHash
}).then(res => res.data);
// 初始化续传状态
uploader.initResumableState(uploadId, uploadedParts);
// 开始/恢复上传
const isCompleted = await uploader.resumeUpload(file);
// 所有分片上传完成:调用合并接口
if (isCompleted) {
await axios.post('/api/upload/complete', { uploadId, fileHash });
console.log('文件上传完成!');
}
};
关键说明
- 依赖服务端返回 uploadId 和已上传分片列表,是断点续传的核心;
- 本地可扩展 localStorage 持久化 uploadId 和已上传分片,适配页面刷新场景;
- 分片重试逻辑可在 uploadSingleChunk 中扩展(指数退避重试,避免高频重试)。
6.7 完整分片上传流程
整体流程(Mermaid 流程图)
#mermaid-svg-v3Rb3Twlzwqv5FVZ{font-family:\”trebuchet ms\”,verdana,arial,sans-serif;font-size:16px;fill:#333;}@keyframes edge-animation-frame{from{stroke-dashoffset:0;}}@keyframes dash{to{stroke-dashoffset:0;}}#mermaid-svg-v3Rb3Twlzwqv5FVZ .edge-animation-slow{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 50s linear infinite;stroke-linecap:round;}#mermaid-svg-v3Rb3Twlzwqv5FVZ .edge-animation-fast{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 20s linear infinite;stroke-linecap:round;}#mermaid-svg-v3Rb3Twlzwqv5FVZ .error-icon{fill:#552222;}#mermaid-svg-v3Rb3Twlzwqv5FVZ .error-text{fill:#552222;stroke:#552222;}#mermaid-svg-v3Rb3Twlzwqv5FVZ .edge-thickness-normal{stroke-width:1px;}#mermaid-svg-v3Rb3Twlzwqv5FVZ .edge-thickness-thick{stroke-width:3.5px;}#mermaid-svg-v3Rb3Twlzwqv5FVZ .edge-pattern-solid{stroke-dasharray:0;}#mermaid-svg-v3Rb3Twlzwqv5FVZ .edge-thickness-invisible{stroke-width:0;fill:none;}#mermaid-svg-v3Rb3Twlzwqv5FVZ .edge-pattern-dashed{stroke-dasharray:3;}#mermaid-svg-v3Rb3Twlzwqv5FVZ .edge-pattern-dotted{stroke-dasharray:2;}#mermaid-svg-v3Rb3Twlzwqv5FVZ .marker{fill:#333333;stroke:#333333;}#mermaid-svg-v3Rb3Twlzwqv5FVZ .marker.cross{stroke:#333333;}#mermaid-svg-v3Rb3Twlzwqv5FVZ svg{font-family:\”trebuchet ms\”,verdana,arial,sans-serif;font-size:16px;}#mermaid-svg-v3Rb3Twlzwqv5FVZ p{margin:0;}#mermaid-svg-v3Rb3Twlzwqv5FVZ .label{font-family:\”trebuchet ms\”,verdana,arial,sans-serif;color:#333;}#mermaid-svg-v3Rb3Twlzwqv5FVZ .cluster-label text{fill:#333;}#mermaid-svg-v3Rb3Twlzwqv5FVZ .cluster-label span{color:#333;}#mermaid-svg-v3Rb3Twlzwqv5FVZ .cluster-label span p{background-color:transparent;}#mermaid-svg-v3Rb3Twlzwqv5FVZ .label text,#mermaid-svg-v3Rb3Twlzwqv5FVZ span{fill:#333;color:#333;}#mermaid-svg-v3Rb3Twlzwqv5FVZ .node rect,#mermaid-svg-v3Rb3Twlzwqv5FVZ .node circle,#mermaid-svg-v3Rb3Twlzwqv5FVZ .node ellipse,#mermaid-svg-v3Rb3Twlzwqv5FVZ .node polygon,#mermaid-svg-v3Rb3Twlzwqv5FVZ .node path{fill:#ECECFF;stroke:#9370DB;stroke-width:1px;}#mermaid-svg-v3Rb3Twlzwqv5FVZ .rough-node .label text,#mermaid-svg-v3Rb3Twlzwqv5FVZ .node .label text,#mermaid-svg-v3Rb3Twlzwqv5FVZ .image-shape .label,#mermaid-svg-v3Rb3Twlzwqv5FVZ .icon-shape .label{text-anchor:middle;}#mermaid-svg-v3Rb3Twlzwqv5FVZ .node .katex path{fill:#000;stroke:#000;stroke-width:1px;}#mermaid-svg-v3Rb3Twlzwqv5FVZ .rough-node .label,#mermaid-svg-v3Rb3Twlzwqv5FVZ .node .label,#mermaid-svg-v3Rb3Twlzwqv5FVZ .image-shape .label,#mermaid-svg-v3Rb3Twlzwqv5FVZ .icon-shape .label{text-align:center;}#mermaid-svg-v3Rb3Twlzwqv5FVZ .node.clickable{cursor:pointer;}#mermaid-svg-v3Rb3Twlzwqv5FVZ .root .anchor path{fill:#333333!important;stroke-width:0;stroke:#333333;}#mermaid-svg-v3Rb3Twlzwqv5FVZ .arrowheadPath{fill:#333333;}#mermaid-svg-v3Rb3Twlzwqv5FVZ .edgePath .path{stroke:#333333;stroke-width:2.0px;}#mermaid-svg-v3Rb3Twlzwqv5FVZ .flowchart-link{stroke:#333333;fill:none;}#mermaid-svg-v3Rb3Twlzwqv5FVZ .edgeLabel{background-color:rgba(232,232,232, 0.8);text-align:center;}#mermaid-svg-v3Rb3Twlzwqv5FVZ .edgeLabel p{background-color:rgba(232,232,232, 0.8);}#mermaid-svg-v3Rb3Twlzwqv5FVZ .edgeLabel rect{opacity:0.5;background-color:rgba(232,232,232, 0.8);fill:rgba(232,232,232, 0.8);}#mermaid-svg-v3Rb3Twlzwqv5FVZ .labelBkg{background-color:rgba(232, 232, 232, 0.5);}#mermaid-svg-v3Rb3Twlzwqv5FVZ .cluster rect{fill:#ffffde;stroke:#aaaa33;stroke-width:1px;}#mermaid-svg-v3Rb3Twlzwqv5FVZ .cluster text{fill:#333;}#mermaid-svg-v3Rb3Twlzwqv5FVZ .cluster span{color:#333;}#mermaid-svg-v3Rb3Twlzwqv5FVZ div.mermaidTooltip{position:absolute;text-align:center;max-width:200px;padding:2px;font-family:\”trebuchet ms\”,verdana,arial,sans-serif;font-size:12px;background:hsl(80, 100%, 96.2745098039%);border:1px solid #aaaa33;border-radius:2px;pointer-events:none;z-index:100;}#mermaid-svg-v3Rb3Twlzwqv5FVZ .flowchartTitleText{text-anchor:middle;font-size:18px;fill:#333;}#mermaid-svg-v3Rb3Twlzwqv5FVZ rect.text{fill:none;stroke-width:0;}#mermaid-svg-v3Rb3Twlzwqv5FVZ .icon-shape,#mermaid-svg-v3Rb3Twlzwqv5FVZ .image-shape{background-color:rgba(232,232,232, 0.8);text-align:center;}#mermaid-svg-v3Rb3Twlzwqv5FVZ .icon-shape p,#mermaid-svg-v3Rb3Twlzwqv5FVZ .image-shape p{background-color:rgba(232,232,232, 0.8);padding:2px;}#mermaid-svg-v3Rb3Twlzwqv5FVZ .icon-shape rect,#mermaid-svg-v3Rb3Twlzwqv5FVZ .image-shape rect{opacity:0.5;background-color:rgba(232,232,232, 0.8);fill:rgba(232,232,232, 0.8);}#mermaid-svg-v3Rb3Twlzwqv5FVZ .label-icon{display:inline-block;height:1em;overflow:visible;vertical-align:-0.125em;}#mermaid-svg-v3Rb3Twlzwqv5FVZ .node .label-icon path{fill:currentColor;stroke:revert;stroke-width:revert;}#mermaid-svg-v3Rb3Twlzwqv5FVZ :root{–mermaid-font-family:\”trebuchet ms\”,verdana,arial,sans-serif;}
失败
成功
否
是
是
否
是
初始化上传
计算文件标识(MerkleRoot/抽样Hash)
调用服务端初始化接口 → 获取 uploadId + 已上传分片列表
文件切片 + 计算分片 Hash
过滤已上传分片(断点续传核心)
PromisePool 并发上传分片
分片上传成功?
自动重试(最多 maxRetryCount 次)
记录分片 ETag/状态
所有分片上传完成?
调用服务端合并分片接口(携带所有分片 ETag)
服务端合并分片 + 校验文件 Hash
Hash 校验通过?
上传完成,返回文件地址
上传失败,返回错误原因
用户暂停/取消?
终止上传,保留已上传分片状态
用户触发恢复上传 → 回到 “过滤已上传分片(断点续传核心)”
核心步骤总结
7. 组件设计
7.1 多端组件规划
| PC 端 | huge-file-upload | 扩展现有 Upload 组件,支持分片配置 |
| Mobile 端 | 大文件上传组件 | 适配移动端交互(暂停 / 恢复 / 进度) |
7.2 移动端 UI 状态设计
#mermaid-svg-tiC5PzKwkB9cjYc6{font-family:\”trebuchet ms\”,verdana,arial,sans-serif;font-size:16px;fill:#333;}@keyframes edge-animation-frame{from{stroke-dashoffset:0;}}@keyframes dash{to{stroke-dashoffset:0;}}#mermaid-svg-tiC5PzKwkB9cjYc6 .edge-animation-slow{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 50s linear infinite;stroke-linecap:round;}#mermaid-svg-tiC5PzKwkB9cjYc6 .edge-animation-fast{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 20s linear infinite;stroke-linecap:round;}#mermaid-svg-tiC5PzKwkB9cjYc6 .error-icon{fill:#552222;}#mermaid-svg-tiC5PzKwkB9cjYc6 .error-text{fill:#552222;stroke:#552222;}#mermaid-svg-tiC5PzKwkB9cjYc6 .edge-thickness-normal{stroke-width:1px;}#mermaid-svg-tiC5PzKwkB9cjYc6 .edge-thickness-thick{stroke-width:3.5px;}#mermaid-svg-tiC5PzKwkB9cjYc6 .edge-pattern-solid{stroke-dasharray:0;}#mermaid-svg-tiC5PzKwkB9cjYc6 .edge-thickness-invisible{stroke-width:0;fill:none;}#mermaid-svg-tiC5PzKwkB9cjYc6 .edge-pattern-dashed{stroke-dasharray:3;}#mermaid-svg-tiC5PzKwkB9cjYc6 .edge-pattern-dotted{stroke-dasharray:2;}#mermaid-svg-tiC5PzKwkB9cjYc6 .marker{fill:#333333;stroke:#333333;}#mermaid-svg-tiC5PzKwkB9cjYc6 .marker.cross{stroke:#333333;}#mermaid-svg-tiC5PzKwkB9cjYc6 svg{font-family:\”trebuchet ms\”,verdana,arial,sans-serif;font-size:16px;}#mermaid-svg-tiC5PzKwkB9cjYc6 p{margin:0;}#mermaid-svg-tiC5PzKwkB9cjYc6 defs #statediagram-barbEnd{fill:#333333;stroke:#333333;}#mermaid-svg-tiC5PzKwkB9cjYc6 g.stateGroup text{fill:#9370DB;stroke:none;font-size:10px;}#mermaid-svg-tiC5PzKwkB9cjYc6 g.stateGroup text{fill:#333;stroke:none;font-size:10px;}#mermaid-svg-tiC5PzKwkB9cjYc6 g.stateGroup .state-title{font-weight:bolder;fill:#131300;}#mermaid-svg-tiC5PzKwkB9cjYc6 g.stateGroup rect{fill:#ECECFF;stroke:#9370DB;}#mermaid-svg-tiC5PzKwkB9cjYc6 g.stateGroup line{stroke:#333333;stroke-width:1;}#mermaid-svg-tiC5PzKwkB9cjYc6 .transition{stroke:#333333;stroke-width:1;fill:none;}#mermaid-svg-tiC5PzKwkB9cjYc6 .stateGroup .composit{fill:white;border-bottom:1px;}#mermaid-svg-tiC5PzKwkB9cjYc6 .stateGroup .alt-composit{fill:#e0e0e0;border-bottom:1px;}#mermaid-svg-tiC5PzKwkB9cjYc6 .state-note{stroke:#aaaa33;fill:#fff5ad;}#mermaid-svg-tiC5PzKwkB9cjYc6 .state-note text{fill:black;stroke:none;font-size:10px;}#mermaid-svg-tiC5PzKwkB9cjYc6 .stateLabel .box{stroke:none;stroke-width:0;fill:#ECECFF;opacity:0.5;}#mermaid-svg-tiC5PzKwkB9cjYc6 .edgeLabel .label rect{fill:#ECECFF;opacity:0.5;}#mermaid-svg-tiC5PzKwkB9cjYc6 .edgeLabel{background-color:rgba(232,232,232, 0.8);text-align:center;}#mermaid-svg-tiC5PzKwkB9cjYc6 .edgeLabel p{background-color:rgba(232,232,232, 0.8);}#mermaid-svg-tiC5PzKwkB9cjYc6 .edgeLabel rect{opacity:0.5;background-color:rgba(232,232,232, 0.8);fill:rgba(232,232,232, 0.8);}#mermaid-svg-tiC5PzKwkB9cjYc6 .edgeLabel .label text{fill:#333;}#mermaid-svg-tiC5PzKwkB9cjYc6 .label div .edgeLabel{color:#333;}#mermaid-svg-tiC5PzKwkB9cjYc6 .stateLabel text{fill:#131300;font-size:10px;font-weight:bold;}#mermaid-svg-tiC5PzKwkB9cjYc6 .node circle.state-start{fill:#333333;stroke:#333333;}#mermaid-svg-tiC5PzKwkB9cjYc6 .node .fork-join{fill:#333333;stroke:#333333;}#mermaid-svg-tiC5PzKwkB9cjYc6 .node circle.state-end{fill:#9370DB;stroke:white;stroke-width:1.5;}#mermaid-svg-tiC5PzKwkB9cjYc6 .end-state-inner{fill:white;stroke-width:1.5;}#mermaid-svg-tiC5PzKwkB9cjYc6 .node rect{fill:#ECECFF;stroke:#9370DB;stroke-width:1px;}#mermaid-svg-tiC5PzKwkB9cjYc6 .node polygon{fill:#ECECFF;stroke:#9370DB;stroke-width:1px;}#mermaid-svg-tiC5PzKwkB9cjYc6 #statediagram-barbEnd{fill:#333333;}#mermaid-svg-tiC5PzKwkB9cjYc6 .statediagram-cluster rect{fill:#ECECFF;stroke:#9370DB;stroke-width:1px;}#mermaid-svg-tiC5PzKwkB9cjYc6 .cluster-label,#mermaid-svg-tiC5PzKwkB9cjYc6 .nodeLabel{color:#131300;}#mermaid-svg-tiC5PzKwkB9cjYc6 .statediagram-cluster rect.outer{rx:5px;ry:5px;}#mermaid-svg-tiC5PzKwkB9cjYc6 .statediagram-state .divider{stroke:#9370DB;}#mermaid-svg-tiC5PzKwkB9cjYc6 .statediagram-state .title-state{rx:5px;ry:5px;}#mermaid-svg-tiC5PzKwkB9cjYc6 .statediagram-cluster.statediagram-cluster .inner{fill:white;}#mermaid-svg-tiC5PzKwkB9cjYc6 .statediagram-cluster.statediagram-cluster-alt .inner{fill:#f0f0f0;}#mermaid-svg-tiC5PzKwkB9cjYc6 .statediagram-cluster .inner{rx:0;ry:0;}#mermaid-svg-tiC5PzKwkB9cjYc6 .statediagram-state rect.basic{rx:5px;ry:5px;}#mermaid-svg-tiC5PzKwkB9cjYc6 .statediagram-state rect.divider{stroke-dasharray:10,10;fill:#f0f0f0;}#mermaid-svg-tiC5PzKwkB9cjYc6 .note-edge{stroke-dasharray:5;}#mermaid-svg-tiC5PzKwkB9cjYc6 .statediagram-note rect{fill:#fff5ad;stroke:#aaaa33;stroke-width:1px;rx:0;ry:0;}#mermaid-svg-tiC5PzKwkB9cjYc6 .statediagram-note rect{fill:#fff5ad;stroke:#aaaa33;stroke-width:1px;rx:0;ry:0;}#mermaid-svg-tiC5PzKwkB9cjYc6 .statediagram-note text{fill:black;}#mermaid-svg-tiC5PzKwkB9cjYc6 .statediagram-note .nodeLabel{color:black;}#mermaid-svg-tiC5PzKwkB9cjYc6 .statediagram .edgeLabel{color:red;}#mermaid-svg-tiC5PzKwkB9cjYc6 #dependencyStart,#mermaid-svg-tiC5PzKwkB9cjYc6 #dependencyEnd{fill:#333333;stroke:#333333;stroke-width:1;}#mermaid-svg-tiC5PzKwkB9cjYc6 .statediagramTitleText{text-anchor:middle;font-size:18px;fill:#333;}#mermaid-svg-tiC5PzKwkB9cjYc6 :root{–mermaid-font-family:\”trebuchet ms\”,verdana,arial,sans-serif;}
初始状态
选择文件后
点击上传
所有分片上传+合并成功
分片上传失败/Hash校验失败
用户点击暂停
用户点击恢复
用户点击重试
关闭/确认
待选择
待上传
上传中
上传完成
上传失败
暂停上传
7.3 组件 Props 设计(TypeScript)
/** 上传文件项类型 */
interface ImageUploadItem {
uid: string;
name: string;
size: number;
status: 'pending' | 'uploading' | 'done' | 'error';
url?: string;
error?: string;
progress: number;
}
/** 上传错误信息类型 */
interface OnErrorInfoType {
file: ImageUploadItem;
error: Error;
message: string;
}
/** 上传进度信息类型 */
interface OnProgressInfoType {
file: ImageUploadItem;
chunkId: number;
chunkProgress: string;
totalProgress: string;
}
/** 上传完成信息类型 */
interface OnFinishInfoType {
file: ImageUploadItem;
url: string;
totalTime: number;
}
/** 大文件上传组件Props */
interface ImageUploadProps {
// 基础控制
value?: ImageUploadItem[]; // 受控文件列表
onChange?: (fileList: ImageUploadItem[]) => void; // 文件列表变更回调
defaultValue?: ImageUploadItem[]; // 非受控默认值
mode: 'view' | 'edit'; // 展示/编辑模式
// 上传核心配置
action: (file: File) => Promise<string> | string; // 上传接口/回调
method: 'GET' | 'POST' | 'PUT'; // 请求方法
data?: (file: File) => Record<string, any> | Promise<Record<string, any>>; // 附加FormData
uploadMode?: 'huge' | 'default'; // 分片/普通上传模式
chunkSize?: number; // 分片大小(byte),默认4MB
maxTryCount?: number; // 分片最大重试次数,默认3
concurrentUploads?: number; // 并发数,默认3
// 文件过滤
accept?: string; // 文件类型限制
multiple?: boolean; // 是否支持多选
maxCount?: number; // 最大文件数
maxSize?: number; // 单文件最大体积
onCountExceed?: (exceed: number) => void; // 超数量回调
onSizeExceed?: (exceed: number) => void; // 超体积回调
// 生命周期回调
beforeUpload?: (file: File, files: File[]) => boolean | Promise<boolean> | File | Promise<File>; // 上传前钩子
onStart?: (file: ImageUploadItem) => void; // 上传开始
onError?: (info: OnErrorInfoType) => void; // 读取/上传错误
onProgress?: (info: OnProgressInfoType) => void; // 进度更新
onFinish?: (info: OnFinishInfoType) => void; // 上传完成
onFinishError?: (errorMsg: string) => void; // 上传失败
// UI配置
layout: 'horizontal' | 'vertical'; // 列表排列方式
disableUpload?: boolean; // 禁用上传
renderItem?: (originNode: React.ReactElement, file: ImageUploadItem, fileList: ImageUploadItem[]) => React.ReactNode; // 自定义渲染项
deleteIcon?: React.ReactNode | false; // 自定义删除图标
previewIcon?: React.ReactNode | false; // 自定义预览图标
retryIcon?: React.ReactNode | false; // 自定义重试图标
// 交互回调
onDelete?: (index: number, item: ImageUploadItem) => boolean | Promise<boolean> | void; // 删除回调
onRetry?: (index: number, item: ImageUploadItem) => Promise<void> | void; // 重试回调
}
8. 埋点指标
| 上传效率 | 单文件总耗时、分片平均耗时 | 评估上传速度优化效果 |
| 成功率 | 整体成功率、分片失败率、重试率 | 评估稳定性 |
| 资源消耗 | 内存占用、CPU 使用率 | 评估前端性能影响 |
| 网络适配 | 不同网络环境(4G / Wi-Fi)表现 | 优化分片 / 并发策略 |
9. 风险预估与遗留问题
9.1 核心风险
| 浏览器兼容性 | 部分浏览器不支持 Web Worker | 降级方案:主线程计算 Hash(提示用户等待) |
| 内存占用过高 | 大文件切片导致内存溢出 | 分片后及时释放内存,限制最大并发数 |
| 云存储接口变更 | 依赖的云存储分段上传 API 变更 | 封装适配层,隔离底层接口变化 |
| 误判文件完整性 | MerkleTree / 抽样 Hash 存在碰撞 | 重要文件仍使用完整 MD5 计算,或增加文件大小校验 |
9.2 遗留问题
10. 外部依赖与限制
11. 上线方案
11.1 灰度策略
11.2 回滚方案
- 紧急回滚:关闭配置中心的“分片上传功能开关”,降级为普通上传;
- 版本回滚:回滚至上线前的稳定版本 Tag。
11.3 开发阶段规划
| 基础功能开发 | 分片上传、并发控制、进度监控 |
| 组件适配 | 扩展现有 Upload 组件,适配 PC / Mobile 端 |
| 性能优化 | Web Worker Hash 计算、动态分片策略 |
| 埋点接入 | 上传耗时 / 成功率埋点,接入监控看板 |
| 灰度验证 | 试点地区上线,收集性能数据 |
| 全量上线 | 扩大灰度范围,全量发布 |


