java - 如何在 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。
这是 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));
}
推荐阅读
- java - firebase 电话身份验证在发布版本中不起作用
- yii - Yii2注册Js set Type并移除jquery
- reactjs - 用打字稿反应上下文
- python - 在 Tensorboard 中组织运行
- ansible - Pervent Ansible 在变量中将 \a 更改为 \u0007
- sql - Postgres 间隔在 where 子查询中不起作用
- javascript - 所有可能的可打印字符
- android - ionic android 平台无法通过 http 与后端通信
- apache-beam - 在 Apache Beam 中结合 vs ParDo
- django - 在一个视图中创建具有 OneToOneField 关系的视图