zoukankan      html  css  js  c++  java
  • springboot获取项目跟目录

     

    springboot部署之后无法获取项目目录的问题:

    之前看到网上有提问在开发一个springboot的项目时,在项目部署的时候遇到一个问题:就是我将项目导出为jar包,然后用java -jar 运行时,项目中文件上传的功能无法正常运行,其中获取到存放文件的目录的绝对路径的值为空,文件无法上传。问题链接

    不清楚此网友具体是怎么实现的,通常我们可以通过如下方案解决:

    //获取跟目录
    File path = new File(ResourceUtils.getURL("classpath:").getPath());
    if(!path.exists()) path = new File("");
    System.out.println("path:"+path.getAbsolutePath());
    
    //如果上传目录为/static/images/upload/,则可以如下获取:
    File upload = new File(path.getAbsolutePath(),"static/images/upload/");
    if(!upload.exists()) upload.mkdirs();
    System.out.println("upload url:"+upload.getAbsolutePath());
    //在开发测试模式时,得到的地址为:{项目跟目录}/target/static/images/upload/
    //在打包成jar正式发布时,得到的地址为:{发布jar包目录}/static/images/upload/
    

    另外使用以上代码需要注意,因为以jar包发布时,我们存储的路径是与jar包同级的static目录,因此我们需要在jar包目录的application.properties配置文件中设置静态资源路径,如下所示:

    #设置静态资源路径,多个以逗号分隔
    spring.resources.static-locations=classpath:static/,file:static/
    

    以jar包发布springboot项目时,默认会先使用jar包跟目录下的application.properties来作为项目配置文件。

  • 相关阅读:
    drf序列化组件
    drf入门规范
    vue发送ajax请求与跨域问题
    Vue对象提供的属性功能
    vue.js库的下载与使用
    admin后台管理与media配置
    Auth认证模块
    学习总结3月11日
    学习总结3月10日
    基于 Spark 的物流企业数据仓库 的设计与实现
  • 原文地址:https://www.cnblogs.com/pejsidney/p/9072354.html
Copyright © 2011-2022 走看看