废话不多说,直接上代码!
HTML部分:
<el-dialog title="导入" :visible.sync="open" class="" append-to-body>
<el-upload
class="upload-demo"
ref="upload"
:multiple="false"
:show-file-list="true"
accept='.xls,.xlsx'
action="#"
:on-preview="handlePreview"
:on-remove="handleRemove"
:before-remove="beforeRemove"
:on-exceed="handleExceed"
:on-change='onChange'
:file-list="fileList"
:limit="1"
:auto-upload="false"
>
<el-button size="small" type="primary">浏览文件el-button>
el-upload>
<el-button style="margin-left: 200px" @click="setUpload" type="primary">上传el-button>
<el-button @click="guanbi">关闭el-button>
el-dialog>
<el-upload>组件属性如下:
:file-list="fileList" 译:上传列表
:multiple="false" 译:是否多选文件
:show-file-list="true" 译:否展示已选择文件列表
accept='.xls,.xlsx' 译:限制上传格式
action="#" 译:上传地址(这里我用ajax上传所以不用)
:on-change='onChange' 译:文件状态改变时的钩子,添加文件、上传成功和上传失败时都会被调用
:limit="1" 译:上传文件个数
:auto-upload="false" 译:是否选择完立即上传文件
上述属性就不一一给大家说明,可参考官方给定的使用文档
点击此处跳转: 官方文档
js部分:
data:function({
return{
fileList: [],
open:false,
}
})
钩子事件部分:
methods:{
handlePreview(file) {
console.log(file)
},
handleExceed(files, fileList) {
this.$message.warning(`当前限制选择 1 个文件,本次选择了 ${files.length} 个文件,共选择了 ${files.length + fileList.length} 个文件`);
},
beforeRemove(file, fileList) {
return this.$confirm(`确定移除 ${file.name}?`);
},
onChange(a, fileList) {
this.fileList = fileList;
},
setUpload() {
debugger
var _this = this;
if(_this.fileList==''){
this.$notify.info({
title: '消息',
message: '请先选择 [浏览文件] 后在点击上传!'
});
}else{
var param = new FormData();
param.append("file", _this.fileList[0].raw);
$.ajax({
url: '/xxx/xxx/setlead',
processData: false,
contentType: false,
type: "post",
data: param,
success: function (res) {
console.log(res.msg)
if(res.msg=='上传成功!'){
_this.succeed();
}
}
})
},
guanbi(){
var _this=this;
_this.open=false
_this.select();
},
},
}
java端部分:
@PostMapping("/setlead")
@ResponseBody
public R importData(@RequestParam("file") MultipartFile file) throws IOException {
ExcelReader reader = cn.hutool.poi.excel.ExcelUtil.getReader(file.getInputStream());
List<UserDO> listData = reader.readAll(UserDO.class);
for (UserDO listDatum : listData) {
userService.insertxs(listDatum);
}
return R.error("上传成功!");
}
Hutool依赖
<dependency>
<groupId>cn.hutoolgroupId>
<artifactId>hutool-allartifactId>
<version>5.8.4version>
dependency>
PS:综上所述如有错误的地方,欢迎在下方评论区指正哦~
本文章内容均为个人编写并通过实际代码落地测试无问题后,方才提供给大家借鉴参考,若搬运请标明出处!