1. void 方法,使用 HttpServletResponse 进行文件下载:
@PostMapping("/downloadFile")
public void downloadFile(HttpServletResponse response) {
byte[] fileData = ;
try (OutputStream outputStream = response.getOutputStream()) {
outputStream.write(fileData);
outputStream.flush();
} catch (IOException e) {
}
}
2. ResponseEntity 方法
@GetMapping("/downloadFile")
public ResponseEntity<org.springframework.core.io.Resource> downloadFile() {
byte[] fileData = ;
InputStreamResource inputStreamResource = new InputStreamResource(new ByteArrayInputStream(fileData));
HttpHeaders headers = new HttpHeaders();
HttpStatus statusCode = ;
return new ResponseEntity<>(inputStreamResource, headers, statusCode);
}
3. StreamingResponseBody 方法:
@GetMapping("/downloadFile")
public StreamingResponseBody downloadFile() {
return outputStream -> {
byte[] fileData = ;
InputStream inputStream = new ByteArrayInputStream(fileData);
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
inputStream.close();
};
}
建议:
- 如果简单性和流传输效率至关重要,而且对HTTP响应的精细控制不是必需的话,第一种方法可能更适合。
- 如果需要更多对HTTP响应的控制、标准化的错误处理和更好的可测试性,那么使用ResponseEntity的第二种方法更为推荐。
- 对于大文件下载,或者需要更高性能和较小内存开销的情况,可以考虑使用StreamingResponseBody的第三种方法。