spring boot实现文件下载
时间: 2023-11-08 09:06:35 浏览: 33
Spring Boot 可以通过使用 HttpServletResponse 对象来实现文件下载。具体步骤如下:
1. 在 Controller 中定义一个下载文件的接口,使用 @RequestMapping 注解指定访问路径。
2. 在接口中使用 HttpServletResponse 对象设置响应头,指定 Content-Disposition 属性为 attachment ,并指定要下载的文件名。
3. 读取要下载的文件,并将文件流写入到 HttpServletResponse 对象的输出流中。
4. 关闭流对象,完成下载。
下面是示例代码:
```
@RequestMapping("/download")
public ResponseEntity<InputStreamResource> downloadFile() throws IOException {
String fileName = "exampleFile.pdf";
ClassPathResource resource = new ClassPathResource(fileName);
HttpHeaders headers = new HttpHeaders();
headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
headers.add("Pragma", "no-cache");
headers.add("Expires", "0");
headers.add("Content-Disposition", "attachment; filename=" + fileName);
headers.add("Content-Type", "application/octet-stream");
headers.add("Content-Length", String.valueOf(resource.contentLength()));
InputStreamResource isr = new InputStreamResource(resource.getInputStream());
return ResponseEntity.ok()
.headers(headers)
.contentLength(resource.contentLength())
.contentType(MediaType.parseMediaType("application/octet-stream"))
.body(isr);
}
```