gpt4 book ai didi

spring boot setContentType 不工作

转载 作者:行者123 更新时间:2023-12-04 11:36:36 27 4
gpt4 key购买 nike

我正在尝试在 spring-boot (1.2.2) 上返回一个图像
我应该如何设置内容类型?
以下都不适合我(意味着响应 header 根本不包含“内容类型” header ):

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

最佳答案

首先,您需要申请 @ResponseBody除了 @RequestMapping 的注释, 除非您使用的是 @RestController在类(class)级别,而不仅仅是 @Controller .另外,试试 produces @RequestMapping 的元素例如

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

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

关于spring boot setContentType 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30708935/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com