• SpringBoot项目打成jar包后上传文件到服务器 目录与jar包同级问题


         看标题好像很简单的样子,但是针对使用jar包发布SpringBoot项目就不一样了。
    当你使用tomcat发布项目的时候,上传文件存放会变得非常简单,因为你可以随意操作项目路径下的资源。但是当你使用SpringBoot的jar包发布项目的时候,你会发现,你不能像以前一样操作文件了。当你使用File file = new File()的时候根本不知道这个路径怎么办。而且总不能很小的项目也给它构建一个文件服务器吧。所以这次就来解决这样的问题

    实现

    因为我们无法操作jar包内容,所以我们只能将文件存放在别的位置,与jar包同级的目录是一个不错的选择。

    首先获取根目录:

    File path = new File(ResourceUtils.getURL("classpath:").getPath());
    if(!path.exists()) {
    path = new File("");
    }

    然后获取需要的目录,我们设定我们需要将文件存放在与jar包同级的static的upload目录下

    File upload = new File(path.getAbsolutePath(),"static/upload/");
    if(!upload.exists()) {
    upload.mkdirs();
    }

    然后当我们要将上传的文件存储的时候,按照下面的方式去新建文件,然后使用你喜欢的方式进行存储就可以了

    File upload = new File(path.getAbsolutePath(),"static/upload/test.jpg");
    FileUtils.copyInputStreamToFile(inputStream, uploadFile);

    不要忘记

    你需要在application.yml配置中加入以下代码,指定两个静态资源的目录,这样你上传的文件就能被外部访问到了。

    spring:
    # 静态资源路径
    resources:
    static-locations: classpath:static/,file:static/
    /*
     **author:weijiakun
     *获取目录工具类
     */
    public class GetServerRealPathUnit {
    
        public static String  getPath(String subdirectory){
            //获取跟目录---与jar包同级目录的upload目录下指定的子目录subdirectory
            File upload = null;
            try {
                //本地测试时获取到的是"工程目录/target/upload/subdirectory
                File path = new File(ResourceUtils.getURL("classpath:").getPath());
                if(!path.exists()) path = new File("");
                upload = new File(path.getAbsolutePath(),subdirectory);
                if(!upload.exists()) upload.mkdirs();//如果不存在则创建目录
                String realPath = upload + "/";
                return realPath;
            } catch (FileNotFoundException e) {
                throw new RuntimeException("获取服务器路径发生错误!");
            }
        }
    }

    springboot项目打成jar包后读取静态资源:

    1:在非静态方法中读取

    InputStream stream = getClass().getClassLoader().getResourceAsStream("test/test.txt");

    2: 在静态方法中读取:

      InputStream resourceAsStream = YourClass.class.getClassLoader().getResourceAsStream("static/position.png");
  • 相关阅读:
    Leetcode Spiral Matrix
    Leetcode Sqrt(x)
    Leetcode Pow(x,n)
    Leetcode Rotate Image
    Leetcode Multiply Strings
    Leetcode Length of Last Word
    Topcoder SRM 626 DIV2 SumOfPower
    Topcoder SRM 626 DIV2 FixedDiceGameDiv2
    Leetcode Largest Rectangle in Histogram
    Leetcode Set Matrix Zeroes
  • 原文地址:https://www.cnblogs.com/dw3306/p/10440735.html
Copyright © 2020-2023  润新知