vue代碼
<el-upload
ref="upload"
action="/api/iot/deviceInfo/uploadFiles"
:before-upload="beforeUploadHandle"
:on-success="handleSuccess"
:auto-upload="false"
multiple
:limit="2"
:on-exceed="handleExceed"
:file-list="fileList">
<el-link :disabled="disabled" icon="el-icon-paperclip" type="primary">添加文檔或視頻</el-link>
</el-upload>
js代碼
// 上傳之前
beforeUploadHandle(file) {
// 校驗格式
if (
file.type !== "video/mp4" &&
file.type !== "application/msword" &&
file.type !==
"application/vnd.openxmlformats-officedocument.wordprocessingml.document"
) {
this.$message.error("只支持.mp4、.doc、.docx文件!");
return false;
}
},
// 超出上傳數(shù)量的時候調(diào)用
handleExceed(files, fileList) {
this.$message.warning(
`當(dāng)前限制選擇 2 個文件,本次選擇了 ${files.length} 個文件,共選擇了 ${
files.length + fileList.length
} 個文件`
);
},
// 手動上傳
submitUpload() {
this.$refs.ruleForm.validate((valid) => {
if (valid) {
if (this.$refs.upload.uploadFiles.length <= 0) {
this.$message.warning("請選擇上傳的文檔或視頻");
return;
}
this.saveLoading = true;
// 新建formData對象
let formData = new FormData();
// 將上傳的文件放進formData對象
this.$refs.upload.uploadFiles.forEach((file) => {
formData.append("file", file.raw);
});
// 攜帶其他參數(shù)
formData.append("articleTitle", this.form.articleTitle);
formData.append("category", this.form.category);
formData.append("author", this.form.author);
formData.append("keyword", this.form.keyword);
formData.append("unit", this.form.unit);
// 調(diào)用上傳接口
uploadFile(formData)
.then((res) => {
if (res && res.code === 200) {
this.$message.success("保存成功");
} else {
this.$message.error(res.msg);
}
this.saveLoading = false;
this.queryRule();
})
.catch((err) => {
console.log(err);
});
this.dialogFormVisible = false;
this.isAdd = false;
}
});
},
使用this.$refs.upload.uploadFiles獲取文件列表是因為通過綁定file-list經(jīng)常獲取不到對象列表,具體原因還不清楚