( 二十七 )、SpringBoot项目打成jar包后上传文件到服务器 目录与jar包同级问题

( 二十七 )、SpringBoot项目打成jar包后上传文件到服务器 目录与jar包同级问题

 

 

1、简介

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

 

2、解决方案

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

2.1、首先获取根目录:

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

 

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

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

 

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

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

 

3、工具类(获取与jar 包同级的路径, 并创建文件夹)

/*
 **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("获取服务器路径发生错误!");
        }
    }
}

 

4、Springboot项目打成jar包后读取静态资源:

1:在非静态方法中读取

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

2: 在静态方法中读取:

  InputStream resourceAsStream = YourClass.class.getClassLoader().getResourceAsStream("static/position.png");

 

posted @ 2019-02-26 22:38  邓维-java  阅读(6395)  评论(1编辑  收藏  举报