data() {
return {
// 上传----------------------------------------
headers: {
token: localStorage.token, //获取token(注意仔细看后端接受token的字段名是不是叫做“token”)
},
actionUrl: "https://xxx.com/import",
fmt: ["xls", "xlsx"],
dur: 100,
percent: 100,
// ----------------------------------------
},
methods: {
// 上传文件----------------------------------------------------------------
showFakeLoading() {
this.interval && clearInterval(this.interval);
this.percent = 0;
this.interval = setInterval(() => {
this.percent++;
this.percent >= 99 && clearInterval(this.interval);
}, this.dur);
}
,
hideFakeLoading() {
this.interval && clearInterval(this.interval);
this.percent = 100;
},
//文件上传之前
beforeFileUpload(file, id) {
// 判断是不是特定的格式________________________
let isFile = this.fmt.includes(file.name.toLocaleLowerCase().split(".").pop());
const maxSize = 50; //限制大小
const isAllowSize = file.size / 1024 / 1024 <= maxSize;
isFile || this.$message.error("上传文件只能是" + this.fmt + "格式");
isAllowSize || this.$message.error("上传文件大小不能超过" + maxSize + "MB");
let allowUpload = isFile && isAllowSize;
allowUpload && this.showFakeLoading(); //虚假加载
if (allowUpload) {
// 为了实现form-data方式上传文件----------------------------------------
let formData = new FormData();
formData.append("file", file);//注意这个位置的一般后端会用file,一般情况不要修改
this.$axios
.post(this.actionUrl, formData, {
headers: {"Content-Type": "multipart/form-data"}
})
.then((d) => {
this.$message.success(`文件“${file.name}”导入成功`);
this.hideFakeLoading();//停止加载
this.initList();//刷新列表
})
.catch((d) => {
this.$message.error("文件导入失败,请稍后再试!");
console.log(d);
});
// ----------------------------------------
}
return allowUpload; //若返回 false则停止上传
}
}