springMVC实现基本文件下载功能

 1 @RequestMapping(value = "download", method = RequestMethod.GET, produces = {MediaType.APPLICATION_JSON_VALUE})
 2 public ResponseEntity<byte[]> download(Long attachmentId) throws Exception {
 3     // ===== 校验入参的合法性 ===== //
 4     CheckParamUtil.checkObjectNotNull(attachmentId, "attachment download attachmentId is null");
 5     Attachment attachment = attachmentService.findOne(attachmentId);
 6     // ===== 判断ID是否有对应的文档记录 ===== //
 7     CheckParamUtil.checkObjectNotNull(attachment, "attachment download findOne attachment is null");
 8     log.info("document download is attachment: {}", attachment);
 9     // ===== 文件名与目录 ===== //
10     String fileName = attachment.getAttachmentName();
11     String filePath = BASE_PATH + attachment.getAttachmentAddress();
12     File file = new File(filePath);
13     HttpHeaders headers = new HttpHeaders();
14     // 为了解决中文名称乱码问题
15     fileName = new String(fileName.getBytes("UTF-8"), "iso-8859-1");
16     headers.setContentDispositionFormData("attachment", fileName);
17     headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
18     return new ResponseEntity<>(FileUtils.readFileToByteArray(file), headers, HttpStatus.CREATED);
19 }

猜你喜欢

转载自www.cnblogs.com/yanwu0527/p/9166547.html