Spring boot setContentType not working

I am trying to return the image to spring-boot (1.2.2)
How to set the content type? Not the following ones work for me (this means that the response headers do not contain the "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); } 
+5
source share
2 answers

Got this ... Had to add ByteArrayHttpMessageConverter to the WebConfiguration class:

 @Configuration @EnableWebMvc @ComponentScan public class WebConfiguration extends WebMvcConfigurerAdapter { @Override public void configureMessageConverters(List<HttpMessageConverter<?>> httpMessageConverters) { httpMessageConverters.add(new ByteArrayHttpMessageConverter()); } } 

And then my second attempt ( getFile3() ) worked correctly

+1
source

First, you need to apply the @ResponseBody annotation in addition to @RequestMapping , unless you use @RestController at the class level, and not just @Controller . Also, try the produces @RequestMapping element, for example.

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

This should “narrow down the primary mapping” and provide the right type of content. See Docs: http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#mvc-ann-requestmapping-produces

+6
source

All Articles