0
点赞
收藏
分享

微信扫一扫

C现代方法(第25章)笔记——国际化特性

往复随安_5bb5 2023-12-15 阅读 39

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的第三种方法。
举报

相关推荐

0 条评论