spring boot setContentType不起作用

时间:2015-06-08 12:16:07

标签: spring spring-boot content-type

我试图在弹簧靴(1.2.2)上返回图像 我该如何设置内容类型? 以下不符合我的要求(意味着响应标头不包含'内容类型'标题):

    @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);
}

2 个答案:

答案 0 :(得分:6)

首先,除了@ResponseBody之外,您还需要应用@RequestMapping注释,除非您在班级而不是@RestController使用@Controller。另外,请尝试produces的{​​{1}}元素,例如

@RequestMapping

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

答案 1 :(得分:1)

知道了...必须将ByteArrayHttpMessageConverter添加到WebConfiguration类:

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

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

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