简体   繁体   中英

How do I write a Spring Controller method that returns an image?

I would like to write a Spring controller method which returns an image from storage. Below is my current version, but it has two problems:

  1. The @GetMapping annotation requires the 'produces' parameter which is a string array of media types. The program does not work if that parameter is not present; it just displays the image data as text. The problem is that if I want to support an additional media type then I have to recompile the program. Is there a way to set up the 'produces' media type from inside the viewImg method?
  2. The code below will display any image type except svg, which will display only the message "The image cannot be displayed because it contains errors". The web browser (Firefox) identifies it as media type "webp". However, if I remove all media types from the 'produces' string array except the "image/svg+xml" entry, the image is displayed.

Please advise how to write a controller method that is more general (so that it works with any media type) and does not have issues with svg media type.

Here is my test code:

@GetMapping(value = "/pic/{id}",
        produces = {
                "image/bmp",
                "image/gif",
                "image/jpeg",
                "image/png",
                "image/svg+xml",
                "image/tiff",
                "image/webp"
        }
)
public @ResponseBody
byte[] viewImg(@PathVariable Long id) {

    byte[] data = new byte[0];
    String inputFile = "/path/to/image.svg";
    try {
        InputStream inputStream = new FileInputStream(inputFile);
        long fileSize = new File(inputFile).length();
        data = new byte[(int) fileSize];
        inputStream.read(data);
    } catch (IOException e) {
        e.printStackTrace();
    }
    return data;
}

I recommend FileSystemResource for handling file contents. You can avoid .contentType(..) started line if you don't want to send Content-Type value.

@GetMapping("/pic/{id}")
public ResponseEntity<Resource> viewImg(@PathVariable Long id) throws IOException {
    String inputFile = "/path/to/image.svg";
    Path path = new File(inputFile).toPath();
    FileSystemResource resource = new FileSystemResource(path);
    return ResponseEntity.ok()
            .contentType(MediaType.parseMediaType(Files.probeContentType(path)))
            .body(resource);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM