Spring MVC: How to return image in @ResponseBody? 

Joined:
08/13/2009
Posts:
172

December 30, 2013 14:40:40    Last update: December 30, 2013 14:42:17
Sample code to return an image as a byte array, with @ResponseBody annotation. Content type is controlled by the produces attribute. Calling HttpServletResponse.setContentType has no effect.
// import org.apache.commons.io.IOUtils;
// import org.springframework.web.bind.annotation.RequestMapping;
// import org.springframework.web.bind.annotation.ResponseBody;

@RequestMapping(value="/image", method={RequestMethod.GET}, produces="image/png")
@ResponseBody public byte[] getImage(HttpServletResponse resp) throws IOException {
        // setContentType is ignored for @ResponseBody. 
        // The content type returned is "application/octet-stream" unless "produces" is set.
	// resp.setContentType("image/jpg");

	InputStream in = servletContext.getResourceAsStream("sample.png");
	try {
	    return IOUtils.toByteArray(in);
	}
	finally {
	    in.close();
	}
}
Share |
| Comment  | Tags