【问题标题】:How to implement partial GET requests in Spring Boot?如何在 Spring Boot 中实现部分 GET 请求?
【发布时间】:2021-09-19 18:47:58
【问题描述】:

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

这行得通。当提到字节范围时,返回 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);
}

【问题讨论】:

    标签: java arrays spring-boot get streaming


    【解决方案1】:

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

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

    就这样吧。

    @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));
    }
    

    【讨论】:

    • 但它返回整个对象。除了 206 代码,我还希望它部分返回对象。
    • 部分返回对象是什么意思?
    • 我在我的请求标头上指定了 0-500 个字节。我希望只返回文件的一部分。不是整个文件。
    • 啊,我明白了。我已经修复了我的解决方案来反映这一点。让我知道这是否正确。
    • 必需的类型是 ResponseEntity 但我提供的是 BodyBuilder
    猜你喜欢
    • 1970-01-01
    • 2019-10-12
    • 2022-01-05
    • 2020-07-12
    • 2020-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-28
    相关资源
    最近更新 更多