spring boot setContentType不起作用

Sho*_*ham 7 spring content-type 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);
}
Run Code Online (Sandbox Code Playgroud)

Tom*_*ing 7

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

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

这应该"缩小主映射"并确保设置正确的内容类型.请参阅文档:http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#mvc-ann-requestmapping-produces

  • 关于您的第二点 - 文档指出:_“此外,使用生产条件确保用于生成响应的实际内容类型尊重生产条件中指定的媒体类型”_。无论如何,这就是它对我的工作方式 - 如果我取出 `produces` 元素,我只会得到 `text/html` 默认内容类型。 (2认同)

Sho*_*ham 1

明白了...必须添加ByteArrayHttpMessageConverterWebConfiguration类中:

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

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

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