How to implement partial GET requests in Spring Boot?

Viewed 157

I'm trying to implement a controller that will accept byte range in the request header and then return a multimedia as a byte array. When returning a file, partial requests are enabled by default.

This works. Returns 206 and part of the file when byte range is mentioned. And 200(and the whole file) when byte range is not mentioned.

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

this doesn't work. It returns 200 whether or not I mention byte range in my request header.

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

Return a ResponseEntity whose status code is 206.

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

So do it like this.

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