1.Controller
@RequestMapping(method = RequestMethod.GET, value = "/download")
@Accessable(name = "附件信息", function = "user", requireRole = true,requireLogin = true)
@ApiOperation(value = "保存附件信息")
@CrossOrigin
void projectDownload(Long id, HttpServletResponse response) {
JsonResult result = this.service.projectDownload(id);
byte[] bytes = (byte[]) result.get("stream");
String extension = (String) result.get("extension");
String downloadName = String.format("附件.%s", extension);
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.DEFAULT.encode(downloadName, StandardCharsets.UTF_8));
response.setContentType("application/octet-stream");
try {
ServletOutputStream stream = response.getOutputStream();
stream.write(bytes);
stream.flush();
stream.close();
} catch (IOException e) {
throw new BusinessException("附件保存出错,请重试");
}
}
2.Service
@Override
public JsonResult projectDownload(Long id) {
PayAttachment entity = setPath.find(PayAttachment.class, id);
try {
if (!ObjectUtils.isEmpty(entity)) {
String filePath = entity.getAttachmentPath();
String absolutePath = String.format("%s%s", uploadFile, filePath);
byte[] bytes = Files.toByteArray(new File(absolutePath));
return JsonResult.ok().put("stream", bytes).put("extension", Files.getFileExtension(filePath));
}
} catch (Exception e) {
throw new BusinessException("保存失败,请重试");
}
return JsonResult.error();
}