代码备忘
// 上传
const fileUpload = async (params) => {
const { file } = params;
const extName = Util.getExtName(file.name);
const typeList = ["zip"];
if (!typeList.includes(extName.toLowerCase())) {
ElMessage.error(`仅支持${typeList.join(",")}文件上传`);
return;
}
const packageSize = 5 * 1024 * 1024; // 分段大小
if (file.size > packageSize) {
// 分段上传
packageUpload(params, packageSize);
} else {
// 单个上传
const formData = new FormData();
formData.append("file", params.file);
try {
//upload
upload.loading = true;
let res = await System.uploadClientPackage(formData, {
onUploadProgress({ event }) {
if (event.lengthComputable) {
upload.percentage = Math.floor((event.loaded / event.total) * 100);
}
},
});
form.value.url = res.data || "";
} finally {
upload.loading = false;
upload.percentage = 0;
}
}
};
// 分段上传
const packageUpload = async (params, packageSize) => {
const { file } = params;
try {
form.value.url = "";
upload.loading = true;
const packageRes = await System.partUploadClientPackage({
fileName: file.name,
fileSize: file.size,
});
const { uploadUrlList = [], ...packageInfo } = packageRes.data || {};
// 分段上传请求列表
upload.percentage = 1; // 假进度给用户反馈
const uploadReqList = uploadUrlList.map((item, index) => {
const formData = new FormData();
formData.append(
"file",
file.slice(index * packageSize, (index + 1) * packageSize)
);
formData.append("uploadUrl ", item);
return new Promise(async (resolve, reject) => {
try {
await System.partUploadShardFile(formData);
const res = await System.getUploadParts({
uploadId: packageInfo.uploadId,
chunkSize: packageInfo.chunkSize,
key: packageInfo.key,
});
// 返回已经上传完成的分段
const list = res.data || [];
const percentage = Math.floor(
(list.length * 100) / uploadUrlList.length
);
// 此项目中进度判断是通过后端接口获取已上传完成的分段数量来计算,在后端接口支持的前提下也可以换成onUploadProgress 来判断
upload.percentage = Math.max(percentage, upload.percentage);
resolve(list);
} catch (error) {
reject(error);
}
});
});
// 上传分段
const list = await Promise.all(uploadReqList);
if (list.some((item) => item.length === uploadUrlList.length)) {
// 合并文件
const res = await System.completeMultipartUpload({
uploadId: packageInfo.uploadId,
chunkSize: packageInfo.chunkSize,
key: packageInfo.key,
});
form.value.url = res.data || "";
upload.percentage = 100;
}
} finally {
upload.percentage = 0;
upload.loading = false;
}
};