springboot保存图片及读取图片

我对springboot不是很熟悉

springboot打包成jar的,后期上传的图片不可能保存到jar里去

我把图片保存到其他系统盘里,跟jar不在一起,这nginx如何读取的到图片

图片用一个单独的路径,nginx 配置中 location 匹配到这个路径,直接访问图片。就是说图片不通过你的 jar 应用程序访问,nginx 直接当图片服务器(静态资源服务器)。

将图片单独配置一个路径,服务保存图片时,保存到这个路径下,然后nginx是支持代理静态资源的,你配置一下就行。

  • 这篇博客: 基于springboot部署jar包通过nginx负载均衡中的 2、springboot打包 部分也许能够解决你的问题, 你可以仔细阅读以下内容或跳转源博客中阅读:
  • 在这里插入图片描述
    在这里插入图片描述

  • 以下回答由chatgpt基于相关博客总结生成:

    在Spring Boot中保存图片并且让Nginx读取这些图片需要以下步骤:

    1.在Spring Boot的配置文件中配置图片保存路径,例如可以将图片保存到其他系统盘中,并且配置该路径到application.properties文件中,即:

    # 图片保存路径配置
    img.path=/other/disk/path/
    

    2.在Spring Boot中保存图片,可以编写一个Controller接收上传的图片并保存,例如:

    @RestController
    public class ImageController {
    
        @Value("${img.path}")
        private String path;
    
        @PostMapping("/uploadImage")
        public String uploadImage(@RequestParam("file") MultipartFile file) throws IOException {
            String fileName = file.getOriginalFilename();
            String dateStr = DateFormatUtils.format(System.currentTimeMillis(), "yyyyMMdd");
            String filePath = path + dateStr + "/";
            File targetFile = new File(filePath);
            if (!targetFile.exists()) {
                targetFile.mkdirs();
            }
            File dest = new File(filePath + fileName);
            file.transferTo(dest);
            return "upload success";
        }
    }
    

    3.Nginx读取保存的图片。在Nginx的配置文件中添加静态资源配置,例如:

    location /images/ {
        alias /other/disk/path/;
        autoindex on;
    }
    

    其中,/images/表示访问的路径,alias后面的路径为图片保存的路径。重启Nginx即可。

    4.如果Nginx需要读取多台服务器上的图片,还需要进行负载均衡配置。在Nginx的配置文件中添加upstream和server配置,例如:

    upstream image_servers{
        server 192.168.1.100:8080 weight=1;
        server 192.168.1.101:8080 weight=1;
    }
    
    location /images/ {
        proxy_pass http://image_servers;
        proxy_redirect default;
    }
    

    其中,upstream配置多个服务器的地址和权重,location配置代理的路径和服务器地址。