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);
}
It's work for me in Spring 4.
By using Spring 3.1.x and 3.2.x, this is how you should do it:
The controller method:
And the mvc annotation in servlet-context.xml file:
I prefere this one:
Change the media type to what ever image format you have.
I think you maybe need a service to store file upload and get that file. Check more detail from here
1) Create a Storage Sevice
2) Create Rest Controller to upload and get file
}
In addition to a couple of answers here a few pointers (Spring 4.1).
Incase you don't have any messageconverters configured in your WebMvcConfig, having
ResponseEntity
inside your@ResponseBody
works well.If you do, i.e. you have a
MappingJackson2HttpMessageConverter
configured (like me) using theResponseEntity
returns aorg.springframework.http.converter.HttpMessageNotWritableException
.The only working solution in this case is to wrap a
byte[]
in the@ResponseBody
as follows:In this case do rememeber to configure the messageconverters properly (and add a
ByteArrayHttpMessageConverer
) in your WebMvcConfig, like so:You should specify the media type in the response. I'm using a @GetMapping annotation with produces = MediaType.IMAGE_JPEG_VALUE. @RequestMapping will work the same.
Without a media type, it is hard to guess what is actually returned (includes anybody who reads the code, browser and of course Spring itself). A byte[] is just not specific. The only way to determine the media type from a byte[] is sniffing and guessing around.
Providing a media type is just best practice