Spring Boot setContentType不起作用 [英] spring boot setContentType is not working
本文介绍了Spring Boot setContentType不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试在spring-boot(1.2.2)上返回映像。
如何设置内容类型?
以下内容都不对我有用(这意味着响应头完全不包含 content-type头):
I'm trying to return an image on spring-boot (1.2.2)
How should I set the content-type?
Non of the following are working for me (meaning that response headers are not containing 'content-type' header at all ):
@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);
}
推荐答案
知道了...将 ByteArrayHttpMessageConverter
添加到 WebConfiguration
类:
Got it... Had to add ByteArrayHttpMessageConverter
to WebConfiguration
class:
@Configuration
@EnableWebMvc
@ComponentScan
public class WebConfiguration extends WebMvcConfigurerAdapter {
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> httpMessageConverters) {
httpMessageConverters.add(new ByteArrayHttpMessageConverter());
}
}
然后我第二次尝试( getFile3()
)正常工作
And the then my second attempt (getFile3()
) was working correctly
这篇关于Spring Boot setContentType不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文