首页 > 解决方案 > 如何在 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);
}

标签: javaarraysspring-bootgetstreaming

解决方案


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

这是 Spring Boot 中 206 的 HTTP 状态代码。

所以就这样做吧。

@RequestMapping("/stream/byte")
public ResponseEntity<byte[]> streamBytes() throws IOException {
    File file = new File("path/to/local/file");
    byte[] fileContent = Files.readAllBytes(file.toPath());
    int numBytes = /** fetch your number of bytes from the header */;
    return ResponseEntity.status(HttpStatus.PARTIAL_CONTENT).body(Arrays.copyOfRange(fileContent, 0, numBytes));
}

推荐阅读