【问题标题】:Spring RestController returns wrong content typeSpring RestController 返回错误的内容类型
【发布时间】: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。

【问题讨论】:

标签: java spring spring-restcontroller


【解决方案1】:
    @GetMapping(path = "/images/{imageKey:.+}")
    public ResponseEntity<Resource> getImageAsResource(
            @PathVariable("imageKey") String imageKey) {
        Resource resource = resourceService.getImage(imageKey);
        Map<String, String> headers = new HashMap<>();
        //Change it based on the type of image your are loading
        headers.put("Content-type", MediaType.IMAGE_JPEG_VALUE);
        return new ResponseEntity<>(resource, headers, HttpStatus.OK);
    }

【讨论】:

  • 关于 Spring 的一件事是肯定的。它从不开箱即用。
【解决方案2】:

在映射中指定方法产生的content type。如果您不需要控制 HTTP 标头和响应代码,请使用 @ResponseBodyannotation。

 @ResponseBody
 @GetMapping(path = "/images/{imageKey:.+}", produces = MediaType. IMAGE_JPEG_VALUE)
 public Resource getImageAsResource(
                         @PathVariable("imageKey") String imageKey) {
    return resourceService.getImage(imageKey);
 }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-04-15
    • 2018-05-15
    • 2019-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-29
    • 1970-01-01
    相关资源
    最近更新 更多