今天讲解一下上传文件。前台必须保持传参类型"multipart/form-data"
后台可以设定
public static final String MULTIPART_FORM_DATA_VALUE = "multipart/form-data";
直接上代码:
@AuthorityAnnotation("game_server_poi") @RequestMapping(value="/gameServerPoi",method = RequestMethod.POST, produces = MediaType.MULTIPART_FORM_DATA_VALUE) public RetResult upload(@RequestParam("file") MultipartFile file,Integer gameId) { if(file.isEmpty()){ return RetResult.error("文件不能为空"); } try { inputStream = file.getInputStream(); XSSFWorkbook workbook = new XSSFWorkbook(inputStream); for (XSSFSheet xssfSheet : workbook) { //处理当前页循环读取每一行 if (xssfSheet == null) { continue; } for (int runNum = 0; runNum < xssfSheet.getLastRowNum() + 1; runNum++) { XSSFRow row = xssfSheet.getRow(runNum); int minColIx = row.getFirstCellNum(); int maxColIx = row.getLastCellNum(); GameServer gameServer = new GameServer(); gameServer.setGameId(gameId); for (int colIx = minColIx; colIx < maxColIx; colIx++) { XSSFCell cell = row.getCell(colIx); cell.setCellType(Cell.CELL_TYPE_STRING); if(colIx == 0){ try { gameServer.setTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(cell.getStringCellValue())); } catch (ParseException e) { e.printStackTrace(); } } if (colIx == 1) { gameServer.setServer(cell.getStringCellValue()); } } gameserverService.insertSelective(gameServer); } } } catch (IOException e) { e.printStackTrace(); }finally { try { inputStream.close(); } catch (IOException e) { e.printStackTrace(); } } return RetResult.success(); }
这段代码比较重要的,就是如何把xlxs字段值取出来, 然后对数据库进行操作。