首先在html里面写入upload的框架
accept参数是限制类型我这里是限制了.xls,.xlsx类型
<el-upload
class="upload-demo"
accept=".xls, .xlsx"
:limit="limitNum"
:auto-upload="false"
:action="UploadUrl()"
:file-list="fileList"
:before-upload="beforeUploadFile"
:on-change="fileChange"
:on-success="fileSuccess"
:on-error="fileError"
:on-exceed="handleExceed"
:show-file-list="false"
multiple
>
<el-button
size="small"
type="primary"
icon="el-icon-circle-plus-outline"
>新增导入</el-button>
</el-upload>
接着data和methods方法
data(){
return{
limitNum: 1, // 上传excell时,同时允许上传的最大数
fileList: [],
}
},
methods: {
// 导入方法
UploadUrl() {
// 设置为一个返回为空的方法
return ''
},
fileSuccess(res, file, fileList) {
this.$message.success('文件上传成功')
},
fileError(err, file, fileList) {
this.$message.success('文件上传失败')
},
beforeUploadFile(file) {
const extension = file.name.substring(file.name.lastIndexOf('.') + 1)
const size = file.size / 1024 / 1024
if (extension !== '.xls') {
this.$message.warning('只能上传excel的文件')
} else if (extension !== '.xlsx') {
this.$message.warning('只能上传excel的文件')
}
if (size > 10) {
this.$message.warning('文件大小不得超过10M')
}
},
// 导入
fileChange(files, fileList) {
this.fileList = []
this.fileList.push(files.raw)
let file = new FormData()
file.append('file', files.raw)
this.$server.apiPost("URL", file).then((res) => {
if (res) {
this.$notify.success("导入成功。");
this.pageInitialization = true
this.form.versionId = res
this.searchForm()
} else {
this.$notify.error("导入失败。");
}
})
},
handleExceed(files, fileList) {
this.$message.warning(`当前限制选择 1 个文件,本次选择了 ${files.length} 个文件,
共选择了 ${files.length + fileList.length} 个文件`);
},
}