A SDK for large file upload with chunking, resumable uploads and instant transfer. Version 2.0 removes endpoint configs and adds customizable functions.
npm install large-file-upload-sdkbash
npm install large-file-upload-sdk
`
$3
`bash
yarn add large-file-upload-sdk
`
$3
`html
`
$3
`bash
npm run build
`
$3
`bash
npm run test
`
然后访问 http://localhost:3000 查看演示。
Then visit http://localhost:3000 to view the demo.
SDK 使用方法 / SDK Usage
$3
`javascript
// ES6 模块引入方式
import FileUploader from 'large-file-upload-sdk';
// 或者在 HTML 中通过 script 标签引入
//
`
$3
`javascript
const uploader = new FileUploader({
// 必须提供自定义函数 / Custom functions are required
checkFileFunction: async (md5, filename) => {
// 检查文件状态的自定义实现 / Custom implementation for checking file status
const response = await fetch('/api/upload/check', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ md5, filename })
});
return response.json();
},
uploadChunkFunction: async (formData) => {
// 上传分片的自定义实现 / Custom implementation for uploading chunk
return fetch('/api/upload/chunk', {
method: 'POST',
body: formData
});
},
mergeFileFunction: async (md5, filename, totalChunks) => {
// 合并文件的自定义实现 / Custom implementation for merging file
const response = await fetch('/api/upload/merge', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ md5, filename, totalChunks })
});
return response.json();
},
// 上传配置(可选) / Upload configuration (optional)
chunkSize: 2 1024 1024, // 分片大小,默认为 2MB / Chunk size, default is 2MB
concurrentFiles: 3, // 最大同时上传文件数,默认为 3 / Max concurrent file uploads, default is 3
concurrentChunks: 3, // 每个文件最大同时上传分片数,默认为 3 / Max concurrent chunk uploads per file, default is 3
maxRetries: 3 // 请求失败最大重试次数,默认为 3 / Max retry attempts for failed requests, default is 3
});
`
$3
| 参数名/Parameter | 类型/Type | 是否必需/Required | 描述/Description |
|-----------------|-----------|------------------|------------------|
| checkFileFunction | (md5: string, filename: string) => Promise | 是/Yes | 用于检查文件状态的函数。接收文件的MD5值和原始文件名,应返回一个Promise,解析为CheckFileResponse对象 |
| uploadChunkFunction | (formData: FormData) => Promise | 是/Yes | 用于上传文件分片的函数。接收包含分片数据的FormData对象,应返回一个Promise,解析为fetch Response对象 |
| mergeFileFunction | (md5: string, filename: string, totalChunks: number) => Promise | 是/Yes | 用于通知服务器合并文件分片的函数。接收文件的MD5值、原始文件名和总分片数,应返回一个Promise,解析为MergeFileResponse对象 |
| chunkSize | number | 否/No | 每个分片的大小(以字节为单位)。默认值为 2MB (2 1024 1024) |
| concurrentFiles | number | 否/No | 最大同时上传的文件数量。默认值为 3 |
| concurrentChunks | number | 否/No | 每个文件最大同时上传的分片数量。默认值为 3 |
| maxRetries | number | 否/No | 请求失败时的最大重试次数。默认值为 3 |
#### CheckFileResponse Interface
`typescript
interface CheckFileResponse {
exists: boolean; // 文件是否已存在(用于秒传)
path?: string; // 文件路径(仅当 exists=true 时)
uploadedChunks: number[]; // 已上传的分片索引数组(仅当 exists=false 时)
}
`
#### MergeFileResponse Interface
`typescript
interface MergeFileResponse {
success: boolean; // 合并操作是否成功
path?: string; // 合并后的文件路径(仅当 success=true 时)
}
`
$3
`javascript
// 添加文件列表(来自 input 或拖拽) / Add file list (from input or drag & drop)
uploader.addFiles(fileList);
`
$3
`javascript
// 取消特定文件的上传 / Cancel upload for a specific file
uploader.cancelUpload(fileId);
`
$3
`javascript
uploader.updateFileStatus = function(fileItem) {
// 在这里更新你的 UI / Update your UI here
console.log(文件 ${fileItem.name}: ${fileItem.status} (${fileItem.progress}%));
console.log(File ${fileItem.name}: ${fileItem.status} (${fileItem.progress}%));
};
`
$3
`javascript
const files = uploader.getFiles();
`
$3
`javascript
// 在组件销毁或页面卸载时调用 / Call when component is destroyed or page is unloaded
uploader.destroy();
`
API 接口规范 / API Specification
服务器需要提供以下三个接口:
The server needs to provide the following three interfaces:
$3
`
POST /api/upload/check
请求体: / Request Body:
{
"md5": "文件MD5值", // File MD5 value
"filename": "原始文件名" // Original filename
}
响应: / Response:
{
"exists": true/false, // 文件是否已存在(秒传) / Whether the file already exists (instant transfer)
"path": "文件路径", // File path (only when exists=true)
"uploadedChunks": [0, 1, 3] // 已上传的分片索引数组(仅 exists=false 时) / Uploaded chunk indices array (only when exists=false)
}
`
$3
`
POST /api/upload/chunk
表单数据: / Form Data:
- file: 分片文件 / Chunk file
- md5: 文件MD5值 / File MD5 value
- chunkIndex: 分片索引 / Chunk index
- totalChunks: 总分片数 / Total chunks
响应: / Response:
{
"success": true
}
`
$3
`
POST /api/upload/merge
请求体: / Request Body:
{
"md5": "文件MD5值", // File MD5 value
"filename": "原始文件名", // Original filename
"totalChunks": 10 // 总分片数 / Total chunks
}
响应: / Response:
{
"success": true,
"path": "文件存储路径" // File storage path
}
``