使用接口实现下载文件,比较简单和优美的写法,敬请参考:
@GetMapping("/{id}")
public ResponseEntity<byte[]> downloadFile(@PathVariable(required = false) Integer id) throws IOException {
Image image = imageService.getById(id);
// 设置下载文件名称,以下两种方式均可
// String fileName = new String(image.getOldname().getBytes("UTF-8"), "iso-8859-1");
String fileName = URLEncoder.encode(image.getOldname(), "utf-8");
HttpHeaders httpHeaders = new HttpHeaders();
// 通知浏览器以下载文件方式打开
ContentDisposition contentDisposition =
ContentDisposition.builder("attachment").filename(fileName).build();
httpHeaders.setContentDisposition(contentDisposition);
// application/octet_stream设置MIME为任意二进制数据
httpHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);
// 使用apache commons-io 里边的 FileUtils工具类
//return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(new File(image.getLocation())),
// httpHeaders, HttpStatus.OK);
// 使用spring自带的工具类也可以 FileCopyUtils
return new ResponseEntity<byte[]>(FileCopyUtils.copyToByteArray(new File(image.getLocation())),
httpHeaders, HttpStatus.OK);
}