英文:
Spring RestController returns wrong content type
问题
我正尝试以以下方式在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 Resource对象返回。然而,Spring将 `Content-Type:` 设置为 `application/json`,而不是根据生成的HTTP响应中的资源设置为正确的 `image/...` 类型。
我如何让Spring从返回的资源中推断出正确的内容类型?
返回的图像资源可以是PNG、JPG或GIF格式。
英文:
I am trying to return an image in a Spring RestController in the following way:
@GetMapping(path = "/images/{imageKey:.+}")
public ResponseEntity<Resource> getImageAsResource(
        @PathVariable("imageKey") String imageKey) {
    Resource resource = resourceService.getImage(imageKey);
    return ResponseEntity.ok(resource);
}
The resourceService returns the image as a Java Resource object. Spring however sets the Content-Type: to application/json instead of the correct image/... type depending on the resource in the generated HTTP response.
How can I make Spring infer the correct content type from the returned resource?
The returned image resource may be a PNG, a JPG or a GIF.
答案1
得分: 2
@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);
}
英文:
    @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);
	}
答案2
得分: 2
在映射方法中指定所生成的内容类型。如果您不需要控制HTTP头和响应代码,请使用@ResponseBody注解。
@ResponseBody
@GetMapping(path = "/images/{imageKey:.+}", produces = MediaType.IMAGE_JPEG_VALUE)
public Resource getImageAsResource(
                         @PathVariable("imageKey") String imageKey) {
    return resourceService.getImage(imageKey);
}
英文:
Specify content type produced by the method in the mapping. Use @ResponseBodyannotation if you don't need control over HTTP headers & response codes.
 @ResponseBody
 @GetMapping(path = "/images/{imageKey:.+}", produces = MediaType. IMAGE_JPEG_VALUE)
 public Resource getImageAsResource(
                         @PathVariable("imageKey") String imageKey) {
    return resourceService.getImage(imageKey);
 }
专注分享java语言的经验与见解,让所有开发者获益!



评论