繁体   English   中英

如何编写返回图像的 Spring Controller 方法?

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

我想写一个 Spring controller 方法,它从存储中返回图像。 以下是我当前的版本,但它有两个问题:

  1. @GetMapping 注解需要 'produces' 参数,它是一个媒体类型的字符串数组。 如果该参数不存在,程序将无法运行; 它只是将图像数据显示为文本。 问题是,如果我想支持其他媒体类型,那么我必须重新编译程序。 有没有办法从 viewImg 方法中设置“生产”媒体类型?
  2. 下面的代码将显示除 svg 之外的任何图像类型,它只会显示消息“图像无法显示,因为它包含错误”。 web 浏览器 (Firefox) 将其识别为媒体类型“webp”。 但是,如果我从“produces”字符串数组中删除除“image/svg+xml”条目之外的所有媒体类型,则会显示图像。

请告知如何编写更通用的 controller 方法(以便它适用于任何媒体类型)并且对 svg 媒体类型没有问题。

这是我的测试代码:

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

我推荐FileSystemResource来处理文件内容。 如果您不想发送Content-Type值,可以避免使用.contentType(..)开始行。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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