<!-- 导入---------------------------------------- -->
<!--注意:action属性是必填项了,这里要加上去,只是在上传过程会报一个错-->
<el-upload
action
:show-file-list="false"
:headers="headers"
:action="actionUrl"
:before-upload="beforeFileUpload"
:disabled="percent < 100"
>
<el-button
type="success"
icon="el-icon-upload"
:loading="percent < 100"
>{{ 100 > percent ? percent + "%" : "导入" }}</el-button>
</el-upload>
<!-- ---------------------------------------- -->
样式_________________________________________________________
// 上传按钮禁用状态----------------------------------------
>>>.el-upload {
cursor: not-allowed;
}
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则停止上传
}
}
elementUI el-upload上传组件实战使用_你挚爱的强哥的博客-CSDN博客- 导入---------------------------------------- -->
https://blog.csdn.net/qq_37860634/article/details/131030401