问题描述
我正在从 DB 获取图像数据(如 byte[]
).如何在 @ResponseBody
中返回这张图片?
I'm getting image data (as byte[]
) from DB. How to return this image in @ResponseBody
?
编辑
我在没有 @ResponseBody
的情况下使用 HttpServletResponse
作为方法参数做到了:
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());
}
使用 @ResponseBody
和注册的 org.springframework.http.converter.ByteArrayHttpMessageConverter
转换器,正如@Sid 所说的那样对我不起作用:(.
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 3.1 或更新版本,您可以在 @RequestMapping
注释中指定produces".下面的示例对我来说是开箱即用的.如果您启用了 web mvc (@EnableWebMvc
),则不需要注册转换器或其他任何东西.
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);
}
这篇关于Spring MVC:如何在@ResponseBody 中返回图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!