elment + vue 文件上传
html页面
<el-upload class="upload-demo" action="/declarationMis/informationManagement/taxpayerInformationManagement/import" :on-preview="handlePreview" //点击已上传的文件链接时的钩子, 可以通过 file.response 拿到服务端返回数据 :on-remove="handleRemove" //文件列表移除文件时的钩子 :before-remove="beforeRemove" //删除文件之前的钩子,参数为上传的文件和文件列表,若返回 false 或者返回 Promise 且被 reject,则停止上传。 :before-upload="beforeAvatarUpload" //上传之前事件, 一般对文件格式,大小做限制 :on-success="handleAvatarSuccess" //成功返回的钩子 multiple :limit="3" //文件个数 :on-exceed="handleExceed" //文件超出个数限制时的钩子 :file-list="fileList"> //上传的文件列表 <el-button size="small" type="primary">点击上传</el-button> <div slot="tip" class="el-upload__tip">只能上传xlsx/xls文件,且不超过2MB</div> </el-upload>
js
handleRemove(file, fileList) { console.log(file, fileList); }, handlePreview(file) { console.log(file); }, handleExceed(files, fileList) { this.$message.warning(`当前限制选择 3 个文件,本次选择了 ${files.length} 个文件,共选择了 ${files.length + fileList.length} 个文件`); }, beforeRemove(file, fileList) { return this.$confirm(`确定移除 ${ file.name }?`); }, handleAvatarSuccess(res, file) { this.$message(res.msg); }, beforeAvatarUpload(file) { // 文件类型进行判断 const isXlsx = file.type === "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; const isXls = file.type === "application/vnd.ms-excel"; const isLt2M = file.size / 1024 / 1024 < 2; if (!(isXlsx||isXls)) { this.$message.error("上传头像图片只能是 xlsx/xls 格式!"); } if (!isLt2M) { this.$message.error("上传头像图片大小不能超过 2MB!"); } return (isXlsx||isXls) && isLt2M; },
controller
public Map<String, Object> importExcel(@RequestParam("file") MultipartFile multipartFile) { LOGGER.info("批量导入,文件开始导入"); Map<String, Object> map = new HashMap<>(); List<TaxpayerEntity> result = Lists.newArrayList(); TaxpayerImportExcel excel = new TaxpayerImportExcel(multipartFile); try { result = excel.analysisExcel(); } catch (Exception e) { map.put("msg", "导入失败!"); LOGGER.error("批量导入失败,原因:{}", e.getMessage()); } if (!result.isEmpty()) { taxpayerService.insertTaxpayerList(result); map.put("msg", " 共计" + result.size() + "条," + "导入成功!"); map.put("code", 0); } else { map.put("msg", " excel无数据,选择有数据的excel进行导入!"); map.put("code", 0); } return map; }