【问题标题】:How do I write a Spring Controller method that returns an image?如何编写返回图像的 Spring Controller 方法?
【发布时间】:2021-04-25 05:45:52
【问题描述】:

我想编写一个从存储中返回图像的 Spring 控制器方法。下面是我目前的版本,但是有两个问题:

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

请告知如何编写更通用的控制器方法(以便它适用于任何媒体类型)并且没有 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;
}

【问题讨论】:

    标签: java spring svg


    【解决方案1】:

    我推荐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);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-06-01
      • 1970-01-01
      • 2018-05-23
      • 2014-05-03
      • 1970-01-01
      • 2023-02-08
      • 2020-07-04
      • 2010-10-08
      相关资源
      最近更新 更多