@RequestMapping(method = RequestMethod.GET, value = "/src/{id}/{filename:.+}")
public ResponseEntity<?> getFile(@PathVariable String id, @PathVariable String filename) {
try {
//通过将给定路径名字符串转换成抽象路径名来创建一个新 File 实例。
//Path.get() 将路径字符串或从路径字符串连接时的字符串序列转换为 Path
File file = new File(Paths.get(this.PIC_FILE_DIRECTORY, id, filename).toString());
//处理显示中文文件名的问题
//通过使用指定的 charset 解码指定的 byte 数组,构造一个新的 String。
String fn = new String(file.getName().getBytes("utf-8"), "ISO-8859-1");
//设置请求头内容
HttpHeaders headers = new HttpHeaders();
//设置响应文件
headers.setContentDispositionFormData("attachment", fn);
//设置相应方式
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
//把文件以二进制形式写回
return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),
headers, HttpStatus.OK);
} catch (Exception e) {
return ResponseEntity.notFound().build();
}
}
下载
最新推荐文章于 2023-02-03 09:56:48 发布