spring - 使用 ResponseEntity<Resource> 发送自定义 Content-Type

标签 spring spring-mvc mime-types content-type

我正在尝试在我的 Spring WebMVC 3.0.5 Controller 中使用 ResponseEntity 返回类型。我正在返回一张图片,所以我想使用以下代码将 Content Type 设置为 image/gif:

@RequestMapping(value="/*.gif")
public ResponseEntity<Resource> sendGif() throws FileNotFoundException {
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.IMAGE_GIF);
    return new ResponseEntity<Resource>(ctx.getResource("/images/space.gif"), headers, HttpStatus.OK);
}

但是,ResourceHttpMessageConverter 中的返回类型被覆盖为 text/html。

除了实现我自己的 HttpMessageConverter 并将其注入(inject) AnnotationMethodHandlerAdapter 之外,我还有什么方法可以强制 Content-Type 吗?

最佳答案

另一个命题:

return ResponseEntity
                  .ok()
                  .contentType(MediaType.IMAGE_GIF)
                  .body(resource);

关于spring - 使用 ResponseEntity<Resource> 发送自定义 Content-Type,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6182362/

相关文章:

java - Consumers 适用于 application/json 但不适用于 text/plain

java - 基于 Spring mvc Java 的配置不起作用。控制台显示没有错误,但我的 jsp 页面没有显示

java - 是否有一个通用的mime类型可以设置为response.setContentType来处理所有类型的文件?

java - 如何在 Spring 中自动重新连接 DataSource 连接?

java - 在 Logback 将 c3po 登录转发到文件

java - 在spring中创建上传功能,出错抛出异常[处理程序处理失败;嵌套异常是 java.lang.StackOverflowError

html - UIWebView 从 <a href=myFileName.myFileType> 下载

java - HTTP 状态 500 - javax.el.PropertyNotFoundException : Property not found on type

java - Spring 休息使用中异常

java - 如何强制 Firefox 使用 java web start 打开页面?