如何在 Spring Boot 中实现部分 GET 请求?

问题描述

我正在尝试实现一个控制器,该控制器将接受请求标头中的字节范围,然后将多媒体作为字节数组返回。返回文件时,认启用部分请求。

这有效。当提到字节范围时,返回 206 和文件的一部分。未提及字节范围时为 200(和整个文件)。

@RequestMapping("/stream/file")
public ResponseEntity<FileSystemResource> streamFile() {
    File file = new File("/path/to/local/file");
    return ResponseEntity.ok().body(new FileSystemResource(file));
}

这不起作用。无论我是否在请求标头中提及字节范围,它都会返回 200。

@RequestMapping("/stream/byte")
public ResponseEntity<byte[]> streamBytes() throws IOException {
    File file = new File("path/to/local/file");
    byte[] fileContent = Files.readAllBytes(file.toPath());
    return ResponseEntity.ok().body(fileContent);
}

解决方法

返回一个状态码为 206 的 ResponseEntity。

Here is the HTTP Status Code for 206 in Spring Boot.

就这样吧。

tab