一尘不染

Spring Boot setContentType不起作用

spring-boot

我正在尝试在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);
}

阅读 943

收藏
2020-05-30

共1个答案

一尘不染

知道了…必须添加ByteArrayHttpMessageConverterWebConfiguration课程:

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

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

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

2020-05-30