【问题标题】:spring boot setContentType is not working春季启动 setContentType 不起作用
【发布时间】:2015-06-08 12:16:07
【问题描述】:

我正在尝试在 spring-boot (1.2.2) 上返回图像
我应该如何设置内容类型? 以下都不对我有用(意味着响应标头根本不包含“内容类型”标头):

    @RequestMapping(value = "/files2/{file_name:.+}", method = RequestMethod.GET)
public ResponseEntity<InputStreamResource> getFile2(final HttpServletResponse response) throws IOException {
    InputStream is = //someInputStream...
    org.apache.commons.io.IOUtils.copy(is, response.getOutputStream());
    response.setContentType("image/jpeg");
    InputStreamResource inputStreamR = new InputStreamResource(is);
    return new ResponseEntity<>(inputStreamR, HttpStatus.OK);
}

@RequestMapping(value = "/files3/{file_name:.+}", method = RequestMethod.GET)
public HttpEntity<byte[]> getFile3() throws IOException {
    InputStream is = //someInputStream...
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.IMAGE_JPEG);
    return new HttpEntity<>(IOUtils.toByteArray(is), headers);
}

【问题讨论】:

  • 请定义“不工作”。
  • @ci_ 我的意思是响应标头根本不包含“内容类型”标头

标签: spring spring-boot content-type


【解决方案1】:

首先,除了@RequestMapping 之外,您还需要应用@ResponseBody 注释,除非您在类级别使用@RestController 而不仅仅是@Controller。另外,尝试@RequestMappingproduces 元素,例如

@RequestMapping(value = "/files2/{file_name:.+}", method = RequestMethod.GET, produces = {MediaType.IMAGE_JPEG_VALUE})

这应该“缩小主映射”并确保设置了正确的内容类型。查看文档:http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#mvc-ann-requestmapping-produces

【讨论】:

  • 我只能这样做 produces = "image/jpeg" 但结果是一样的(响应头根本不包含 'content-type' 头),而且我认为这仅适用于 narrow the primary mapping不要 ensure the correct content type is set
  • 刚刚更正了产品中的 MediaType 值 - 正如您指出的那样,应该是字符串版本。据我所知,从我自己的尝试来看,这应该可以工作——即使没有@ResponseBody,因为你要返回一个实体。你是否取出了手动设置内容类型标题的代码?顺便说一句,我使用了您的第二个尝试解决方案(使用 HttpEntity&lt;byte[]&gt; 进行测试)
  • 关于您的第二点 - 文档指出:“此外,使用产生条件可确保用于生成响应的实际内容类型尊重产生条件中指定的媒体类型”我>。无论如何,这就是它对我的工作方式 - 如果我取出 produces 元素,我只会得到 text/html 默认内容类型。
【解决方案2】:

知道了...必须将ByteArrayHttpMessageConverter 添加到WebConfiguration 类:

@Configuration
@EnableWebMvc
@ComponentScan
public class WebConfiguration extends WebMvcConfigurerAdapter {

@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> httpMessageConverters) {
    httpMessageConverters.add(new ByteArrayHttpMessageConverter());
}
}

然后我的第二次尝试 (getFile3()) 工作正常

【讨论】:

  • 太好了.. 可能是由于 SpringBoot 版本不同(我们使用的是 1.2.3),但使用produces 不需要注册额外的字节数组转换器.. 它可以正常工作。
  • @tombola82 我认为这是因为 @Configuration 注释覆盖了 spring 的许多默认设置。在我添加 ByteArrayHttpMessageConverter 之前,我还可以通过删除 @Configuration 注释来完成这项工作...
  • hmm.. 我对此并不完全相信 ;-) 我们还在配置类上使用 @Configuration(与 @SpringBootApplication 一起启用自动配置和 that 提供了很多默认配置) - 仍然没有字节数组消息转换器存在..它“正常工作”。 @Configuration 不是 spring-boot 注解,只是 java config 的 spring 框架。但是你有一个解决方案,所以这是最重要的!
猜你喜欢
  • 2015-01-22
  • 1970-01-01
  • 1970-01-01
  • 2018-09-04
  • 2017-04-28
  • 2018-06-12
  • 1970-01-01
  • 2017-03-07
  • 2021-08-10
相关资源
最近更新 更多