springboot 大文件输出到response
时间: 2023-08-21 08:01:36 浏览: 146
在 Spring Boot 中,你可以将大文件输出到 response 中,以提高处理效率和减少内存占用。以下是一个示例代码:
```java
@GetMapping("/downloadFile")
public void downloadFile(HttpServletResponse response) throws IOException {
// 1. 获取文件
File file = new File("path/to/your/file");
// 2. 设置 response
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment; filename=" + file.getName());
response.setContentLength((int) file.length());
// 3. 输出文件
try (InputStream inputStream = new BufferedInputStream(new FileInputStream(file))) {
byte[] buffer = new byte[1024];
OutputStream outputStream = response.getOutputStream();
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
} catch (IOException e) {
e.printStackTrace();
}
}
```
在这个示例中,我们首先获取要下载的文件,然后设置 response 的相关信息,包括文件类型、文件名和文件大小。最后,我们使用 InputStream 和 OutputStream 将文件内容输出到 response 中。需要注意的是,在处理文件时,我们使用了 try-with-resources 语句块,以确保文件和流被正确地关闭。