公司没有做自己的文件服务器,用了七牛云。有时候需要上传或者下载一些大的文件,也没有用qiniu-sdk,查了下 axios 的文档,发现有onDownloadProgress , onUploadProgress 这两个配置,可以拿到当前的上传/下载进度。
大概类似这样。直接贴代码./**
*
* @param {*} file input拿到的file
* @param {*} type 文件后缀
* @param {*} cb 监控进度条callback
* @param {*} errorCb 错误回调
*/
export const qiniuUpload = async (file,cb,errorCb) =>{
//获取文件后缀
const sufix = getFileSufix(file.name);
const token_url = `${CONFIG.qiniu_token_url}/1/?prefix=zone`;
const params = {
type: sufix || '',
}
if(!params.type){
delete params.type
}
const response = await API.get(token_url,params);
const data = new FormData();
const key = response.data.data.fileKey;
const host = response.data.bucket_url;
data.append('token', response.data.data[0].token);
data.append('file', file);
const res = await axios({
url: CONFIG.qiniu_url,
method: 'post',
//回调上传回调事件 progressEvent 可以拿到当前loaded以及total.计算出大小以及进度条
onUploadProgress(progressEvent){
if(progressEvent.lengthComputable && cb){
cb(progressEvent)
}
},
data: data,
//timeout一般默认为5000ms,上传大文件时会超时,这里设置没有超时时间
timeout: 0,
withCredentials: false,
headers: {'Content-Type': 'multipart/form-data', 'Access-Control-Allow-Origin': '*'},
}).catch((e) =>{
if(errorCb){
errorCb();
}
});
if(res.status ===200){
const fileUrl = host + "/" + res.data.key
const result = {
status: res.status,
fileUrl: fileUrl,
}
return result;
}else{
return {status:400}
}
}
复制代码
没有做断点续传功能,凑合着用