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包后读取静态资源:

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

 

转载于:https://www.cnblogs.com/dw3306/p/10440735.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值