dndc-chunk-upload
v1.0.5
Published
分片上传
Downloads
2
Keywords
Readme
背景
大文件上传,采用分片上传方式进行解决
安装
npm i dndc-chunk-upload -D
初始化
返回初始化后的ChunkUpload实例
import ChunkUpload from 'dndc-chunk-upload';
const chunkUpload = new ChunkUpload(option);
| 参数名 | 必填 | 类型 | 默认值 | 备注 | | -------------- | ---- | ------- | ----------- | ----------------------------| | chunkURL | 是 | string | - | 分块接口 | | mergeURL | 是 | string | - | 合并接口 | | headers | 是 | Object | - | 携带uploaduuid和Authorization | | chunkSize | 否 | string | 2 * 1024 * 1024(2M) | 分块大小 |
方法
- .on(event, callback) 监听事件
- .off(event, callback) 移除事件监听
事件
success
,上传成功时触发,e = {status: 'done', response: '接口返回内容'}
fail
,上传失败时触发,e = {errCode: 'error', response: '接口返回内容'}
complete
,上传成功或失败时触发,返回值同success
或fail
progess
,上传进度变化时触发,100%
上传示例
import React from 'react';
import ChunkUpload from 'dndc-chunk-upload';
import { getToken } from '@/utils/auth';
const { UPLOAD_DOMAIN, UPLOAD_UUID } = GLOBAL_VARS;
const uploadDemo = () => {
const handleFileChange = e => {
const inputEl = e.target;
const file = inputEl.files[0];
const chunkUpload = new ChunkUpload({
chunkURL: `${UPLOAD_DOMAIN}/upload-chunk/image`,
mergeURL: `${UPLOAD_DOMAIN}/upload-merge-chunks/image`,
headers: {
uploaduuid: UPLOAD_UUID,
Authorization: getToken(),
},
file,
});
// 文件上传成功
chunkUpload.on('success', ({ response }) => {
console.log('upload success', response);
});
// 文件上传失败
chunkUpload.on('fail', res => {
console.log('upload fail', res);
});
// 成功或失败都会触发
chunkUpload.on('complete', res => {
console.log('complete', res);
});
// 文件进度变化
chunkUpload.on('progress', res => {
console.log('progress', res);
});
};
return <input onChange={handleFileChange} type="file" />;
};
export default uploadDemo;
antd upload上传示例
特殊场景结合antd样式
import React from 'react';
import { Upload } from 'antd';
import { getToken } from '@/utils/auth';
const { UPLOAD_DOMAIN, UPLOAD_UUID } = GLOBAL_VARS;
const uploadDemo = () => {
const beforeUpload = file => {
const chunkUpload = new ChunkUpload({
chunkURL: `${UPLOAD_DOMAIN}/upload-chunk/image`,
mergeURL: `${UPLOAD_DOMAIN}/upload-merge-chunks/image`,
headers: {
uploaduuid: UPLOAD_UUID,
Authorization: getToken(),
},
file,
});
// 文件上传成功
chunkUpload.on('success', ({ response }) => {
console.log('upload success', response);
});
// 文件上传失败
chunkUpload.on('fail', res => {
console.log('upload fail', res);
});
// 成功或失败都会触发
chunkUpload.on('complete', res => {
console.log('complete', res);
});
// 文件进度变化
chunkUpload.on('progress', res => {
console.log('progress', res);
});
return false;
};
return (
<Upload beforeUpload={beforeUpload}>
<Button>上传</Button>
</Upload>
)
};
export default uploadDemo;
常见问题
文件类型限制
在文件上传中使用accept
属性限制类型
- 不限制图片格式:
accept="image/*"
- 限制视频文件mp4格式:
accept="video/mp4"
- 多种格式限制:
accept="image/*,video/mp4"
接口API文档
分片上传使用场景
- 一般广告图、头像、封面等普通图片,使用普通上传即可
- 大于10M的文件