項目中需要將圖片放在磁盤上,不能將圖片放在webapp下面!
springboot默認配置基本上可以滿足我們的日常需要。但是項目中大量用戶上傳的圖片,不能放在tomcat下面,這樣子每次重新部署項目的時候,圖片就失效了,很是麻煩。
所以此時就需要自定義配置springboot的項目靜態文件映射
springboot默認的配置規則
映射 /** 到
1
2
3
4
|
classpath:/ static classpath:/ public classpath:/resources classpath:/meta-inf/resources |
到本地文件路徑也就是 resource/static/ 下面
訪問時可以:localhost:8080/+資源路徑+資源名
例如我的項目結構!
此時我訪問的靜態資源為:
localhost:8080/js/jquery.min.js
如果配置 jquery.min.js 直接在static下面 訪問則是
localhost:8080/jquery.min.js
但現在需要自定義映射規則:
有兩種方法一種是基于配置文件,另一種是基于代碼層面配置。
1 基于配置文件
1
2
3
|
#配置內部訪問地址和外部圖片訪問地址 /myimgs/** spring.mvc. static -path-pattern=/** spring.resources. static -locations=file:c:/users/tizzy/desktop/img/,classpath:/ static / |
映射 /** 到 本地磁盤路徑下存放的圖片,和tomcat中的圖片路徑
訪問路徑則是
1
2
|
localhost: 8080 /jquery.min.js localhost: 8080 / 圖片名 |
2 基于代碼層面配置
1
2
3
4
5
6
7
8
9
10
11
12
13
|
@configuration public class webmvcconfiguration extends webmvcconfigureradapter { @override public void addresourcehandlers(resourcehandlerregistry registry) { //addresourcehandler是指你想在url請求的路徑 //addresourcelocations是圖片存放的真實路徑 registry.addresourcehandler( "/**" ).addresourcelocations( "file:d://user/" ).addresourcelocations( "classpath:/static/" ); super .addresourcehandlers(registry); } } |
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:https://segmentfault.com/a/1190000018065349