SpringBoot文件导出功能笔记,不常用,记一下。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| @RequestMapping(value = "/download", method = {RequestMethod.GET,RequestMethod.POST}) public ResponseEntity<ByteArrayResource> download(@RequestParam(name = "id", required = true) Long id){
String workNo = getWorkNo(); if (StringUtils.isEmpty(workNo)) { return new ResponseEntity<>(null, HttpStatus.FORBIDDEN); } if (!checkCenterAuth(workNo)) { return new ResponseEntity<>(null, HttpStatus.FORBIDDEN); }
String fileName = ""; byte[] bytes = null; try{ String filePath = xxxService.export2Excel(id); Path path = Paths.get(filePath); fileName = path.getFileName().toString(); bytes = Files.readAllBytes(path); }catch(Exception e){ return new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR); }
ByteArrayResource bar = new ByteArrayResource(bytes); return ResponseEntity.ok() .contentType(MediaType.APPLICATION_OCTET_STREAM) .header("Content-disposition", "attachment; filename="+fileName) .body(bar); }
|
注意ByteArrayResource有个坑 ,其getDescription()方法返回的并不是设置的description ,增加了描述:
1 2 3 4
| @Override public String getDescription() { return "Byte array resource [" + this.description + "]"; }
|
放入json解析挂了,只能自己继承了。