Spring-mvc – Spring MVC: How to return image in @ResponseBody

spring-mvc

I'm getting image data (as byte[]) from DB. How to return this image in @ResponseBody ?

EDIT

I did it without @ResponseBody using HttpServletResponse as method parameter:

@RequestMapping("/photo1")
public void photo(HttpServletResponse response) throws IOException {
    response.setContentType("image/jpeg");
    InputStream in = servletContext.getResourceAsStream("/images/no_image.jpg");
    IOUtils.copy(in, response.getOutputStream());
}

Using @ResponseBody with registered org.springframework.http.converter.ByteArrayHttpMessageConverter converter as @Sid said doesn't work for me :(.

@ResponseBody
@RequestMapping("/photo2")
public byte[] testphoto() throws IOException {
    InputStream in = servletContext.getResourceAsStream("/images/no_image.jpg");
    return IOUtils.toByteArray(in);
}

Best Answer

if you are using Spring version of 3.1 or newer you can specify "produces" in @RequestMapping annotation. Example below works for me out of box. No need of register converter or anything else if you have web mvc enabled (@EnableWebMvc).

@ResponseBody
@RequestMapping(value = "/photo2", method = RequestMethod.GET, produces = MediaType.IMAGE_JPEG_VALUE)
public byte[] testphoto() throws IOException {
    InputStream in = servletContext.getResourceAsStream("/images/no_image.jpg");
    return IOUtils.toByteArray(in);
}