Spring MVC: How to return image in @ResponseBody?

2019-01-02 19:13发布

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);
}

标签: spring-mvc
14条回答
何处买醉
2楼-- · 2019-01-02 20:16

This is how I do it with Spring Boot and Guava:

@RequestMapping(value = "/getimage", method = RequestMethod.GET, produces = MediaType.IMAGE_JPEG_VALUE)
public void getImage( HttpServletResponse response ) throws IOException
{
    ByteStreams.copy( getClass().getResourceAsStream( "/preview-image.jpg" ), response.getOutputStream() );
}
查看更多
荒废的爱情
3楼-- · 2019-01-02 20:17
 @RequestMapping(value = "/get-image",method = RequestMethod.GET)
public ResponseEntity<byte[]> getImage() throws IOException {
    RandomAccessFile f = new RandomAccessFile("/home/vivex/apache-tomcat-7.0.59/tmpFiles/1.jpg", "r");
    byte[] b = new byte[(int)f.length()];
    f.readFully(b);
    final HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.IMAGE_PNG);


    return new ResponseEntity<byte[]>(b, headers, HttpStatus.CREATED);



}

Worked For Me.

查看更多
登录 后发表回答