<el-upload
ref="upload"
action="123"
accept=".xls, .xlxs,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel"
:auto-upload="false"
:on-change="imgPreview"
:on-success="fileSuess"
:file-list="fileList"
:limit="1"
>
<!-- :on-remove="handleRemove" -->
<el-button size="small" type="primary" icon="el-icon-plus" style="background-color: white;border: 1px solid #DCDFE6;color: #606266;border-radius: 4px;">点击上传</el-button>
<div slot="tip" class="el-upload__tip">只能上传xls/xlxs文件</div>
</el-upload>
使用el-upload中的:auto-upload="false"阻止自动上传
使用el-upload中的on-change事件控制是否上传的是excel文件并且判断特殊字符(实际开发中可以不用判断文件名中存在特殊字符,因为后端使用阿里云附件服务器文件名有特殊字符不能上传)
URL.createObjectURL是el-upload中提供的方法生成一个bolb文件路径,
this.flieUrl 用于在页面显示选中的图片
imgPreview(file, fileList) {
let fileName = file.name;
let regex = /(.xls|.xlsx)$/;
if (regex.test(fileName.toLowerCase())) {
// 判断特殊字符
if(fileName.lastIndexOf('+') == -1){
this.flieUrl = URL.createObjectURL(file.raw);
// this.ImpEmployee.silder_image = file.url;
// console,log(this.file)
}else{
this.$message.error("文件名存在特殊字符,请修改文件名");
this.fileList = [];
}
} else {
this.$message.error("请选择Excel文件");
}
//console.log('图片上传事件')
this.ImpEmployee.silderFile = file.raw;
console.log(this.flieUrl)
console.log(this.fileList)
},
SubmitImpEmployee(){
this.isdisabled = true;
this.$refs.ImpEmployee.validate(valid => {
if (valid) {
if(this.ImpEmployee.silderFile != undefined && this.ImpEmployee.silderFile != ""){
const formData = new FormData()
formData.append('file',this.ImpEmployee.silderFile)
formData.append('areaId',this.ImpEmployee.areaId)
ImportExcel(formData)
.then(response => {
this.isdisabled = false
if(response.data.type =='success'){
this.dialogImpEmployee = false
this.getList()
this.$confirm('已经批量导入成功,点击确定查看导入结果', '成功', {
confirmButtonText: '查看',
cancelButtonText: '取消',
type: 'success'
}).then(() => {
this.$router.push({ path: '/employee/ImpEmployeDetail', query: { id: response.data.id }})
})
}
})
.catch(err => {
});
}else{
this.isdisabled = false;
this.$message({
type:'warning',
message:"请选择需要导入的文件!"
})
return;
}
} else {
this.isdisabled = false;
console.log("error submit!!");
return;
}
});
},
使用表单提交时如果必须上传文件时,再对获取的文件做判断,然后使用FormData对象向后台传递数据