springboot cotroller 下载本地文件
导入hutool maven依赖
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.8.16</version>
</dependency>
下载文件controller代码片段
@GetMapping(“/pics/{path}”)
public ResponseEntity<byte[]> getFile(@PathVariable(“path”) Long path) {
try {
File file = FileUtil.file(path);
if (file.exists() && file.canRead()) {
byte[] fileContent = FileUtil.readBytes(file);
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + path + "\"")
.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_OCTET_STREAM_VALUE)
.body(fileContent);
} else {
return ResponseEntity.notFound().build();
}
} catch (Exception e) {
return ResponseEntity.badRequest().build();
}
}