Spring REST – returning image or a file

Just an example of how to return an image or a file from a rest controller. Idea can be to proxy image call or just to return a file.

@GetMapping(value="/scans/{id}/{image}", produces = MediaType.IMAGE_JPEG_VALUE)
public ResponseEntity<?> getScanImage(@PathVariable String id, @PathVariable String image) {
    final byte[] imageBytes = bucketApi.readScan(UUID.fromString(id), image);
    return new ResponseEntity<>(imageBytes, HttpStatus.OK);
}

@GetMapping(value="/scans/stream/{id}/{image}", produces = MediaType.IMAGE_JPEG_VALUE)
public void getScanImageStream(@PathVariable String id, @PathVariable String image, HttpServletResponse response) throws IOException {
    response.setContentType(MediaType.IMAGE_JPEG_VALUE);
    final InputStream imageInputStream = bucketApi.readScanStream(UUID.fromString(id), image);
    StreamUtils.copy(imageInputStream, response.getOutputStream());
}


@GetMapping(value = "/scans/file/{id}/{fileName}", produces = "text/json")
public ResponseEntity getFile(@PathVariable String id, @PathVariable(value = "fileName") String fileName, HttpServletResponse response) throws IOException {
    final byte[] imageBytes = bucketApi.readScan(UUID.fromString(id), fileName);
    return ResponseEntity.ok()
            .header("Content-Disposition", "attachment; filename=" + fileName ) //+ ".json"
            .contentType(MediaType.APPLICATION_JSON)
            .body
}

Example on GitHub.