【问题标题】:Spring boot rest serve images and other filesSpring Boot 休息服务图像和其他文件
【发布时间】:2021-07-21 10:22:56
【问题描述】:

我想问一下只提供这样的静态内容是否是一种好方法

spring.web.resources.static-locations=classpath:/static/

所以用户会去

  localhost:8080/images/image.png

或者更好的选择

@GetMapping(value = "/image/{image}")
public void userImage(HttpServletResponse response, @PathVariable String image) {
    Path path = Paths.get("src\\main\\resources\\static\\UsersImages\\" + image);
    response.setContentType(MediaType.IMAGE_JPEG_VALUE);

    try {
        InputStream is = Files.newInputStream(path);
        IOUtils.copy(is, response.getOutputStream());
    }catch (Exception e){
        throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR,"Error while streaming image!");
    }
}

我想将它用于用户图像..

将来我也想提供视频等。

谢谢

【问题讨论】:

  • 静态内容已从该位置自动提供。您基本上是在解决已经存在的功能。

标签: spring spring-boot rest


【解决方案1】:

如果您想在未来改进甚至扩展它,服务方法可能是最好的。我建议路径应该是一个属性值,而不是那个可能会在将来破坏实现的长字符串。

【讨论】:

    【解决方案2】:

    对我来说,url 应该没有文件扩展 see there。 您可以准备几个端点,一个用于图像,第二个用于视频,另一个用于 pdf 文件等。

    文件,我会保存在其他位置,如 sftp 服务器、DMS 存储库或云中。 如果你是新手,你可以尝试放在项目之外的某个文件夹中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-02-11
      • 2018-12-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-27
      • 2017-10-27
      相关资源
      最近更新 更多