springboot 访问jar同级别下的文件访问问题

最近使用springboot打包上传的时候遇到一个问题,就是访问与jar同级别的文件,之前使用最多的是war形式,所以很好设置静态资源路径。

但是jar是看不到里面的文件夹的,所以把文件上传到与jar同级别的upload下,这样就需要在项目中设置upload也应该是静态资源。

 

关键代码

//静态资源配置
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        //需要配置1:--- 需要告知系统,这是要被当成静态文件的!  设置内部静态资源
        //第一个方法设置访问路径前缀,第二个方法设置资源路径
        registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
        registry.addResourceHandler("/upload/**").addResourceLocations("classpath:/upload/");
        registry.addResourceHandler("/templates/**").addResourceLocations("classpath:/templates/");
     //关键在这
        //  获取与jar同级目录下的upload文件夹  设置与jar同级静态资源配置
        ApplicationHome h = new ApplicationHome(this.getClass());
        // 本地获取的路径 D:\idea\springboot2.x\target  upload 跟 项目jar平级
        String path = h.getSource().getParent();
        String realPath = path + "/upload/";
        registry.addResourceHandler("/upload/**").addResourceLocations("file:"+realPath);
    }

设置好之后,还遇到了一个问题,css,js加载不了,因为我使用的是nginx处理的静态资源,也要将这些进行代理,代码如下

server {
  listen 80;
  server_name springboot.kingsuper.net;
  access_log /data/wwwlogs/springboot.kingsuper.net_nginx.log combined;
  index index.html index.htm index.jsp;
  root /data/wwwroot/springboot.kingsuper.net;
  
  #error_page 404 /404.html;
  #error_page 502 /502.html;
  
  location ~ .*\.(gif|jpg|jpeg|png|bmp|swf|flv|mp4|ico)$ {
    proxy_pass http://127.0.0.1:8080;
    expires 30d;
    access_log off;
  }

  location ~ .*\.(js|css)?$ {
    proxy_pass http://127.0.0.1:8080;
    expires 7d;
    access_log off;
  }

  location ~ /\.ht {
    deny all;
  }
  
  location ~ {
    proxy_pass http://127.0.0.1:8080;
    include proxy.conf;
  }
}

设置好之后,就可以访问了,over

 

转载于:https://www.cnblogs.com/SeaWxx/p/10935209.html

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值