Monday, March 17, 2014

Spring MVC Serving Images - An Unreasonable PITA

I tried returning a @ResponseBody BufferedImage, but Spring kept returning an HTTP status 406.

Here's how I ended up solving the problem WITHOUT using the BufferedImageHttpMessageConverter (which seems to be a poorly documented method).
   
    @RequestMapping(value = "/{id}.jpg",
                    method = RequestMethod.GET)
    @ResponseBody
    @Secured("ROLE_READ")
    public ResponseEntity<byte[]> get(@PathVariable Long id)
                                  throws Exception {

        // Load it from disk
        File imageFile = new File(...);
        
        try {
            HttpHeaders headers = new HttpHeaders();
            headers.add("Content-Type", "image/jpg");

            byte[] bytes = FileUtils.getBytes(imageFile);

            return new ResponseEntity(bytes, headers,
                                      HttpStatus.NOT_FOUND);
        } catch (IOException e) {
            log.log(Level.INFO, "Couldn't load image file: " +
                                imageFile.getAbsolutePath(), e);

            throw e;
        }
    }

No comments: