【发布时间】:2020-11-14 08:54:48
【问题描述】:
我正在尝试通过以下方式在 Spring RestController 中返回图像:
@GetMapping(path = "/images/{imageKey:.+}")
public ResponseEntity<Resource> getImageAsResource(
@PathVariable("imageKey") String imageKey) {
Resource resource = resourceService.getImage(imageKey);
return ResponseEntity.ok(resource);
}
resourceService 将图像作为 Java 资源对象返回。然而,Spring 将 Content-Type: 设置为 application/json 而不是正确的 image/... 类型,具体取决于生成的 HTTP 响应中的资源。
如何让 Spring 从返回的资源中推断出正确的内容类型?
返回的图片资源可能是 PNG、JPG 或 GIF。
【问题讨论】:
-
最好的办法是将你的资源转换成字节数组stackoverflow.com/a/27969156/4423647。如果你使用spring资源接口,我猜你可以从资源类中获取输入流
-
像'produces = MediaType.IMAGE_PNG_VALUE'一样明确设置
标签: java spring spring-restcontroller