el-upload组件上传
原创大约 3 分钟
介绍了如何使用ElementUI的el-upload组件实现文件上传导入功能,包括H ML部分、JavaScript部分和钩子事件处理,以及Java端接收上传文件的处理。通过简单易懂的代码示例,展示了实现文件上传导入功能的步骤。

ElementUI: el-upload组件上传文件导入功能的实现,简单易懂!
废话不多说,直接上代码!
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下return是为了防止数据污染
data:function({
return{
fileList: [],
//弹窗
open:false,
}
})
钩子事件部分:
methods: {
uploadFile() {
alert('上传文件')
// this.$refs.upload.submit()
//确认上传
var _this = this
//如果没有选择文件则不允许点击,并给出提示选择文件后点击上传按钮
if (_this.fileList === '') {
this.$notify.info({
title: '消息',
message: '请先选择 [浏览文件] 后在点击上传!'
})
} else {
//创建formData对象
var param = new FormData()
// 将文件append到formData对象
param.append(_this.fileList[0].name, _this.fileList[0].raw)
this.upload(param)
$.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()
},
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
}
}
java端部分:
/**
*
* lxt 20022-7-6
*
* */
@PostMapping("/setlead")
@ResponseBody
public R importData(@RequestParam("file") MultipartFile file) throws IOException {
//使用hutool工具类导入Excel文件
ExcelReader reader = cn.hutool.poi.excel.ExcelUtil.getReader(file.getInputStream());
//读取excel中的数据,与User实体类一一对应
List<UserDO> listData = reader.readAll(UserDO.class);
//批量存入数据库中
for (UserDO listDatum : listData) {
//执行插入方法
userService.insertxs(listDatum);
}
//userTaskService.saveImportTask(listData);
return R.error("上传成功!");
}
Hutool依赖
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.8.4</version>
</dependency>