業務需求:
批量導入Excel文件
實現方式:
使用組件upload
具體步驟:
1、引入組件:
<el-upload
accept=".xlsx, .xls" //文件類型
:file-list="fileList" //存儲文件的數組
:action="actionUrl" //請求的url
:before-upload="beforeUploadFile" //文件上傳之前的鉤子
:on-exceed="exceedFile" //文件超出個數時的鉤子
:on-success="uploadSuccess" //文件上傳成功時的鉤子
:show-file-list="isShowFile" //是否顯示文件上傳列表
multiple //支持多文件上傳
:limit="limitNum" //文件上傳個數限制
>
<el-button type="primary" style="margin-left:0px">導入Excel</el-button>
</el-upload>
2、data中定義:
fileList: [], //excel 文件列表
limitNum: 3, //選擇文件個數
actionUrl: "/api/teach/importCourse", //上傳文件url
isShowFile: false //文件列表是否顯示 默認不顯示
3、methods中方法:
//文件上傳之前的鉤子
beforeUploadFile(file) {
console.log("before upload");
console.log(file.size);
var FileExt = file.name.replace(/.+\./, "");
if (["xls", "xlsx"].indexOf(FileExt.toLowerCase()) === -1) {
this.$message({
type: "warning",
message: "請上傳後綴名爲xls、xlsx的附件!"
});
return false;
}
//file.size 以字節爲單位
this.isLt2k = file.size / 2048 < 100 ? "1" : "0";
if (this.isLt2k === "0") {
this.$message({
message: "上傳文件大小不能超過100k!",
type: "error"
});
}
return this.isLt2k === "1" ? true : false;
},
//文件超出個數時的鉤子
exceedFile(files, fileList) {
console.log("文件超出個數:", files);
this.$message.warning(
`只能選擇 ${this.limitNum} 個文件,當前共選擇了 ${files.length +
fileList.length} 個`
);
},
//文件上傳成功時的鉤子
uploadSuccess(response, file, fileList) {
console.log("上傳文件", response.data);
console.log("返回狀態", response.code);
console.log(fileList);
if (response.code != "0000") {
this.excelData = response.data;
this.exportErrorFile();
return this.$message.error("導入失敗!");
} else {
this.isShowFile = true;
return this.$message.success("導入成功!");
}
},