Spring MVC:如何在@ResponseBody中返回图像?
我正在从数据库获取图像数据(作为byte[]
)。如何在 @ResponseBody
中返回此图像?
编辑
我没有使用@ResponseBody
使用HttpServletResponse
作为方法参数来做到这一点:
@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 @Sid 所说的 .springframework.http.converter.ByteArrayHttpMessageConverter
转换器对我不起作用:(。
@ResponseBody
@RequestMapping("/photo2")
public byte[] testphoto() throws IOException {
InputStream in = servletContext.getResourceAsStream("/images/no_image.jpg");
return IOUtils.toByteArray(in);
}
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);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(15)
在您的应用程序上下文中声明 AnnotationMethodHandlerAdapter 并注册ByteArrayHttpMessageConverter:
也在处理程序方法中为您的响应设置适当的内容类型。
In your application context declare a AnnotationMethodHandlerAdapter and registerByteArrayHttpMessageConverter:
also in the handler method set appropriate content type for your response.
为我工作。
Worked For Me.
您应该在响应中指定媒体类型。我正在使用 @GetMapping 注释和 Produces = MediaType.IMAGE_JPEG_VALUE。 @RequestMapping 的工作原理相同。
如果没有媒体类型,就很难猜测实际返回的内容(包括任何读取代码的人、浏览器,当然还有 Spring 本身)。 byte[] 只是不具体。从 byte[] 确定媒体类型的唯一方法是嗅探和猜测。
提供媒体类型只是最佳实践
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
这对我来说是 Spring 4 的工作。
It's work for me in Spring 4.
没有一个答案对我有用,所以我设法这样做:
设置
Content-Disposition
标头我能够使用@ResponseBody
注释下载文件按我的方法。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.这就是我使用 Spring Boot 和 Guava 的方式:
This is how I do it with Spring Boot and Guava:
在 Spring 4 中,您不需要对 beans 进行任何更改,这非常容易。仅将您的返回类型标记为@ResponseBody。
示例:-
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:-
我认为您可能需要一项服务来存储文件上传并获取该文件。
从此处查看更多详细信息
1 ) 创建存储服务
2) 创建 Rest Controller 来上传和获取文件
}
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
}
将 Produce 与 MediaType.IMAGE_JPEG_VALUE 一起使用时,请确保返回 byte[],而不是 Byte[]。很奇怪,但是spring无法转换它并引发异常:找不到转换器。
When using produces with MediaType.IMAGE_JPEG_VALUE, make sure that you are returning byte[], but not Byte[]. Very strange, but spring cannot convert it and raises an exception: no converter found.
如果您使用 Spring 3.1 或更高版本,您可以在 @RequestMapping 注释中指定“products”。下面的例子对我来说是开箱即用的。如果您启用了 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
).使用 Spring 4.1 及更高版本,您可以非常简单地返回几乎任何内容(例如图片、pdf、文档、jar、zip 等),而无需任何额外的依赖项。例如,以下可能是从 MongoDB GridFS 返回用户个人资料图片的方法:
需要注意的事项:
以 InputStreamResource 作为返回类型的 ResponseEntity
ResponseEntity 构建器样式创建
使用此方法,您不必担心 HttpServletResponse 中的自动装配、抛出 IOException 或复制流数据。
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.
除了注册
ByteArrayHttpMessageConverter
之外,您可能还想使用ResponseEntity
而不是@ResponseBody
。以下代码对我有用:In addition to registering a
ByteArrayHttpMessageConverter
, you may want to use aResponseEntity
instead of@ResponseBody
. The following code works for me :通过使用 Spring 3.1.x 和 3.2.x,您应该这样做:
控制器方法:
以及 servlet-context.xml 文件中的 mvc 注释:
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:
除了几个答案之外,这里还有一些提示(Spring 4.1)。
如果您没有在 WebMvcConfig 中配置任何消息转换器,则在
@ResponseBody
中使用ResponseEntity
效果很好。如果您这样做,即您使用
ResponseEntity
配置了MappingJackson2HttpMessageConverter
(像我一样),则返回org.springframework.http.converter.HttpMessageNotWritableException
。在这种情况下,唯一可行的解决方案是将
byte[]
包装在@ResponseBody
中,如下所示:在这种情况下,请记住正确配置消息转换器(并添加 < code>ByteArrayHttpMessageConverer) 在您的 WebMvcConfig 中,如下所示:
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:我更喜欢这个:
将媒体类型更改为您拥有的任何图像格式。
I prefere this one:
Change the media type to what ever image format you have.