如何在spring boot中实现部分get请求?

o75abkj4  于 2021-08-20  发布在  Java
关注(0)|答案(1)|浏览(280)

我正在尝试实现一个控制器,它将接受请求头中的字节范围,然后以字节数组的形式返回多媒体。返回文件时,默认情况下会启用部分请求。
这很有效。当提到字节范围时,返回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);
}
knsnq2tg

knsnq2tg1#

返回状态代码为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));
}

相关问题