自定义上传图片到服务器出现了上传失败的问题

1、上传路径没改动

这里在上传的时候发现存入路径是windows版本的

           //读取原始文件名
            String fileName = file.getOriginalFilename();
            //获取后缀名
            String suffixName = fileName.substring(fileName.lastIndexOf("."));
            //构造新文件名称
            String objectName = UUID.randomUUID() + suffixName;
            log.info("上传的文件名为:" + objectName);
            // 设置文件存储路径(G盘),你可以存放在你想要指定的路径里面。
            String filePath = "C://local//upload//";
            String path = filePath + objectName;
            File dest = new File(path);
            // 检测是否存在目录
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdirs();// 新建文件夹
            }
            file.transferTo(dest);// 文件写入
            String url = "http://localhost:8080/upload/" + objectName;
            return Result.success(url);

这里改动为String filePath = "/services/img/upload/";

2、返回的路径是固定的,这一点在上传到linux服务器上就失效了

          InetAddress ip = InetAddress.getLocalHost();
          log.info(String.valueOf(ip.getHostAddress()));
          String url = "http://" + ip.getHostAddress() + ":8080/upload/" + objectName;

请注意,这段代码可能不会总是按预期工作,因为它依赖于环境和安全设置。在某些情况下,例如在容器化环境或者有特殊网络配置的环境中,它可能无法正确检索到本机的IP地址。

3、改动文件路径后忘记设置根路径

这里有两种方法,一是在配置资源文件中设置静态资源设置,spring.resources.static-locations=file:/path/to/your/static/
二是自定义映射规则,可以使用WebMvcConfigurer接口来自定义规则

 protected void addResourceHandlers(ResourceHandlerRegistry registry) {
        log.info("开始设置静态资源映射...");
        registry.addResourceHandler("/doc.html").addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
        //registry.addResourceHandler("/upload/**").addResourceLocations("file:C://local//upload//");
        registry.addResourceHandler("/upload/**").addResourceLocations("file:/services/img/upload/");
    }

在配置项里面设置静态资源的映射

posted @ 2024-05-09 14:53  码下流年  阅读(43)  评论(0)    收藏  举报