前端
html
<el-upload class="upload-demo" :action="excelAction" :data="uploadPostData" :on-preview="handlePreview" :on-remove="handleRemove" :before-remove="beforeRemove" :on-success="handleSuccess" :headers="uploadHeaders" multiple :limit="1" :on-exceed="handleExceed" :file-list="fileList" style="margin-top: 10px;width: 100%;"> <div style="display: flex;"> <div class="fileNameClass"><el-tag>所导入文件</el-tag> {{ fileName }}</div> <el-button size="small" type="primary" style="margin-left: 10px;height: 43px;">文件上传</el-button> </div> <div slot="tip" class="el-upload__tip" style="color: red;"> 只能上传xlxs、xls文件,且不超过50MB </div> </el-upload>
数据声明
passengerFlowImportDialogVisible: false, //文件上传地址(后端接受文件的地址) excelAction: BASE_URL + "/shift-scheduling-calculate-service/schedulingTask/uploadExcelFile", //所导入的文件名 fileName: "", //文件列表 fileList: [], //导入文件的同时向后台提交数据 uploadPostData: {}, //上传文件的请求头 uploadHeaders: { token: "", },
方法
handleSuccess(res) { this.fileName = res.fileName; }, 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}?`); }, //清除已经上传的文件 clearFileList() { this.fileList = []; }, //退出对话框 exitExcelImport() { this.passengerFlowImportDialogVisible = false; this.clearFileList() }
样式
.fileNameClass { margin-bottom: 30px; border: 1px solid #235ada; padding: 5px; border-radius: 5px; width: 400px; text-align: left; }
后端
/** * 导入excel文件并完成解析 * * @param multipartFile * @param paramMap * @return * @throws Exception */ @PostMapping("/uploadExcelFile") public R uploadExcelFile(@RequestParam(value = "file", required = true) MultipartFile multipartFile, @RequestParam(required = false) Map paramMap) throws Exception { if (multipartFile.isEmpty() || multipartFile.getSize() > 52428800) { R.error(ResultCodeEnum.FAIL.getCode(), "上传文件不能为空,且不能大于50MB"); } String originalFilename = multipartFile.getOriginalFilename(); if (!(originalFilename.endsWith(".xlsx") || originalFilename.endsWith(".xls"))) { return R.error(ResultCodeEnum.FAIL.getCode(), "只能导入xlsx、xls文件"); } InputStream inputStream = multipartFile.getInputStream(); Workbook workbook; if (originalFilename.endsWith(".xlsx")) { workbook = new XSSFWorkbook(inputStream); } else { workbook = new HSSFWorkbook(inputStream); } return R.ok().addData("fileName", originalFilename); }
效果