我正在尝试在spring-boot(1.2.2)上返回映像。 如何设置内容类型?以下任何一种都不适合我(这意味着响应头完全不包含“ content-type”头):
@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课程:
ByteArrayHttpMessageConverter
WebConfiguration
@Configuration @EnableWebMvc @ComponentScan public class WebConfiguration extends WebMvcConfigurerAdapter { @Override public void configureMessageConverters(List<HttpMessageConverter<?>> httpMessageConverters) { httpMessageConverters.add(new ByteArrayHttpMessageConverter()); } }
然后,我的第二次尝试(getFile3())工作正常
getFile3()