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

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

我正在尝试实现一个控制器,它将接受请求头中的字节范围,然后以字节数组的形式返回多媒体。返回文件时,默认情况下会启用部分请求。
这很有效。当提到字节范围时,返回206和文件的一部分。如果不提及字节范围,则为200(以及整个文件)。

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

这不管用。无论我是否在请求头中提到字节范围,它都返回200。

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

knsnq2tg1#

返回状态代码为206的responseentity。
下面是spring boot中206的http状态代码。
所以就这样做吧。

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

相关问题