最近使用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:ideaspringboot2.x arget 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