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)
首先,@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
明白了...必须添加ByteArrayHttpMessageConverter到WebConfiguration类中:
@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())工作正常
| 归档时间: |
|
| 查看次数: |
8439 次 |
| 最近记录: |