需求:
在做公司文件共享系統的項目的時候,遇到個單次上傳最大個數10的需求。
過程:
去翻了文檔,看到limit這個屬性,美滋滋的加上了。自測了下,選擇11個確實執行了on-exceed對應的方法,提示出來超出限制。
提測階段:
測試突然說我這個限制有bug,最后測試確實是存在bug,原因是文檔這個limit是疊加上傳的文件個數,而不是每次。並且upload組件,默認上傳多個的方式是,調用多次接口。(例如上傳5個文件,調用5次)。這肯定也是不行的。 於是看到
了http-request屬性,使用他覆蓋默認上傳行為。

解決方案:
直接貼代碼了。需要注意的是,記得及時清空已上傳的文件列表fileLIs。 代碼寫的比較爛,看思路就好 哈哈哈

submitUpload() {
//調用組件上傳方法
this.$refs.upload.submit();
let { uploadFiles } = this.$refs.upload;
// 1.個數校驗
let fileLen = uploadFiles.length;
if (fileLen == 0) {
this.$message.error("請先選擇文件!");
return false;
}
if (fileLen > 10) {
this.$message.error(`一次最多上傳10個文件!`);
this.$refs.upload.clearFiles();
return false;
}
// 校驗文件
let form = new FormData();
let fileNameArr = [];
let status = false;
uploadFiles.forEach((item, index) => {
// 2.格式校驗
const imgSuffixReg = /(mp3|mp4|MP4|mpg|flv|doc|docx|xls|xlsx|ppt|pptx|pdf|jpg|JPG|jpeg|png|PNG|zip)$/;
const point = item.name.lastIndexOf(".");
const suffix = item.name.substr(point + 1);
const isImg = imgSuffixReg.test(suffix);
const isLt500M = item.size / 1024 / 1024;
let imgFlag = true;
if (!isImg) {
this.$message.error(
`請上傳 mp3 mp4 mpg flv word excel ppt pdf jpg jpeg png zip 格式文件!`
);
imgFlag = false;
status = true;
}
// 3.大小校驗
let sizeFlag = true;
if (isLt500M > 500) {
this.$message.error("上傳文件大小不能超過 500MB!");
sizeFlag = false;
status = true;
}
// 符合條件加入formData
if (imgFlag && sizeFlag) {
form.append("fileUploads", item.raw);
fileNameArr.push(item.name);
}
});
form.append("parentId", this.parentId);
// 任意一個不符合規則都不上傳,直接返回
if (status) {
this.$refs.upload.clearFiles();
return false;
}
// 調用接口是否文件重復
checkFj({
parentId: this.parentId,
fileNames: fileNameArr
}).then(res => {
if (res.code === 200) {
// 上傳服務器
uploadFileApi(form).then(res => {
// 清空文件列表
this.$refs.upload.clearFiles();
if (res.code === 200) {
this.$message.success("上傳成功!");
this.fetchDataList();
}
});
} else {
this.$refs.upload.clearFiles();
}
});
},
接口:

