Vue中El-upload上传文件的使用方法
写法
函数
<template>
<div>
<el-upload
class="upload-demo"
ref="upload"
accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, .xlsx, application/vnd.ms-excel"
action="11"
name="upfile"
:limit="2"
:before-upload="beforeUpload"
:on-change="handleChange"
:file-list="fileList"
:auto-upload="false"
>
<el-button slot="trigger" size="small" type="primary">选取文件</el-button>
<el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传到服务器</el-button>
<div slot="tip" class="el-upload__tip">只能上传excel文件,且不超过10MB</div>
</el-upload>
</div>
</template>
<script>
// import appConfig from "../../config/config";
export default {
data() {
return {
fileList: [],
freshen: true,
nweFileList: this.fileList,
dialogEditOrAddData: ""
};
},
methods: {
handleChange(file, fileList) {
if (fileList.length > 0) {
this.fileList = [fileList[fileList.length - 1]]; // 这一步,是 展示最后一次选择的文件
}
},
beforeUpload(file) {
let extensionArr = file.name.split(".")
const extension = extensionArr[extensionArr.length-1] === "xlsx";
const extension2 = extensionArr[extensionArr.length-1] === "xls";
const isLt10M = file.size / 1024 / 1024 < 10;
if (!extension && !extension2) {
this.$message.warning("上传模板只能是 xls、xlsx格式!");
return;
}
if (!isLt10M) {
this.$message.warning("上传模板大小不能超过 10MB!");
return;
}
this.fileName = file.name;
let fd = new FormData();
fd.append("upfile", file); //传文件
this.$https.post("/api/answer/importAnswer", fd).then(res => {
if (res.data.success === false) {
this.freshen = false;
this.$emit("Listfreshen", this.freshen);
this.$message.error(res.data.data);
this.$refs.upload.clearFiles();
} else {
this.$message.success("上传成功");
this.freshen = true;
this.$emit("Listfreshen", this.freshen);
this.$refs.upload.clearFiles();
}
});
return false; //屏蔽了action的默认上传
},
submitUpload() {
this.$refs.upload.submit();
}
}
};
</script>