vue项目使用element组件上传excel文件
有写需求一个一个的新增太慢了,所以需要以文件形式大量数据导入
html部分
选取文件
{{btn.message}}
上传文件只能为excel文件,且为xlsx,xls格式
//此处可以写导入时出现的详细错误信息,包含第几行出现问题显示出来
{{ o.message }}
data部分
data() {
return {
importDialogVisible: false,
//文件
file: "",
filename: "",
limit: 1,
filelist: [],
errmesg: [],
btn: {
disable: false,
message: "上传服务器",
},
}
}
弹窗方法
impoortExcel() {
let that = this;
that.importDialogVisible = true;
},
选择文件方法
handleExceed(e) {
// 判断是否只能上传一个文件,超过提示报错
console.log(e);
this.$notify.error({
title: "错误",
message: "只能上传一个文件哦",
});
},
handleChansge(file, fileList) {
console.log(file);
let name = file.name;
if (!/\.(xlsx|xls|XLSX|XLS)$/.test(file.name)) {
this.$notify.error({
title: "错误",
message: "上传文件只能为excel文件,且为xlsx,xls格式",
});
this.filelist = [];
this.file = "";
return false;
}
this.file = file.raw;
this.filename = file.name;
},
上传文件方法
postfile() {
let that = this;
if (this.file == "") {
that.$notify.error({
title: "错误",
message: "上传文件不能为空",
});
return false;
} else {
// 文件形式的需要用 formData形式
let formData = new FormData();
formData.append("file", this.file);
let url = "接口地址";
let config = {
headers: { "Content-Type": "multipart/form-data" },
};
this.btn.disable = true;
this.btn.message = "上传中,请等待";
this.$axios1
.post(url, formData, config)
.then(function (response) {
console.log(response);
that.$notify({
title: "成功",
message: response.data.message,
type: "success",
});
that.filelist = [];
that.btn.disable = false;
that.btn.message = "上传服务器";
})
.catch((err) => {
that.btn.disable = false;
that.btn.message = "上传服务器";
that.$notify.error({
title: "错误",
message: "上传过程出错啦",
});
});
}
},
效果展示
页面展示
上传成功之后 根据后台返回数据自行处理