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);
}
In your application context declare a AnnotationMethodHandlerAdapter and registerByteArrayHttpMessageConverter:
also in the handler method set appropriate content type for your response.
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
).Non of the answers worked for me, so I've managed to do it like that:
Setting
Content-Disposition
header I was able to download the file with the@ResponseBody
annotation on my method.In addition to registering a
ByteArrayHttpMessageConverter
, you may want to use aResponseEntity
instead of@ResponseBody
. The following code works for me :In spring 4 it's very easy you don't need to make any changes in beans. Only mark your return type to @ResponseBody.
Example:-
With Spring 4.1 and above, you can return pretty much anything (such as pictures, pdfs, documents, jars, zips, etc) quite simply without any extra dependencies. For example, the following could be a method to return a user's profile picture from MongoDB GridFS:
The things to note:
ResponseEntity with InputStreamResource as a return type
ResponseEntity builder style creation
With this method you dont have to worry about autowiring in the HttpServletResponse, throwing an IOException or copying stream data around.