什么是靜態(tài)資源路徑?
靜態(tài)資源路徑是指系統(tǒng)可以直接訪問的路徑,且路徑下所有文件均可被用戶直接讀取。
在springboot中默認(rèn)的靜態(tài)資源路勁有:classpath:/META-INF/resources/
, classpath:/static/
, classpath:/public/
, classpath:/resources/
從這里看出這里的靜態(tài)資源都在classpath下
那么問題來了,如果上傳的文件放在上述的文件夾中會有怎樣的后果?
1 網(wǎng)站的數(shù)據(jù)和代碼不能有效分離
2 當(dāng)項目打成jar包,上傳的圖片會增加jar的大小,運行效率降低
3 網(wǎng)站數(shù)據(jù)備份變得復(fù)雜
將自定義的外部目錄,掛載為靜態(tài)目錄
此時可以將靜態(tài)資源路徑設(shè)置到磁盤的某個目錄
1 在springboot中可以直接在配置文件中覆蓋默認(rèn)的靜態(tài)資源路徑的配置信息:
application.properties配置如下:
web.upload-path=D:/temp/images/
springboot.mvc.static-path-pattern=/**
spring.resources.static-locations=classpath:/META-INF/resources/,classpath:/static,classpath:/resources/,file:{web.upload-path}
注意: 這個web.upload-path是屬于自定義的一個屬性,指定一個路徑,注意要以/結(jié)尾;
spring.mvc.static-path-parttern=/** 表示所有的訪問經(jīng)過靜態(tài)資源路徑
spring.resources.static-locations在這里配置靜態(tài)資源路徑,前面說了這里的配置是覆蓋默認(rèn)配置,所以需要加上默認(rèn)的,否則static,public這些路徑
將不能被當(dāng)作靜態(tài)資源路徑,在這個末尾的file:{web.upload-path}之所以加file:是因為指定的是一個具體的硬盤路徑,classpath值系統(tǒng)環(huán)境變量
處理文件上傳的掛載目錄, 并且以自定義的URI訪問上傳的文件
通過靜態(tài)資源配置類實現(xiàn),繼承WebMvcConfigurerAdapter
package com.sam.demo.conf;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
/**
* 配置靜態(tài)資源映射
* @author sam
* @since 2017/7/16
*/
@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
//將所有/static/** 訪問都映射到classpath:/static/ 目錄下
//addResourceLocations的每一個值必須以'/'結(jié)尾,否則雖然映射了,但是依然無法訪問該目錄下的的文件(支持: classpath:/xxx/xx/, file:/xxx/xx/, http://xxx/xx/)
registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
}
}
重啟項目,訪問:http://localhost:8080/static/c.jpg 能正常訪問static目錄下的c.jpg圖片資源
springboot項目獲取文件的絕對路徑
獲取根目錄
File path=new File(ResourceUtils.getURL("classpath:").getPath());
if(!path.exists()){
path=new File("");
}
//如果上傳目錄為/static/images/upload/,則可以如下獲取
File upload=new File(path.getAbsolutePath(),"static/images/uplaod/");
if(!upload.exists()){
upload.mkdirs();
System.out.println(upload.getAbsolutePath());
//在開發(fā)測試模式時,得到地址為:{項目跟目錄}/target/static/images/upload/
//在打成jar正式發(fā)布時,得到的地址為:{發(fā)布jar包目錄}/static/images/upload/
}
注意點
另外使用以上代碼需要注意,因為以jar包發(fā)布時,我們存儲的路徑是與jar包同級的static目錄,因此我們需要在jar包目錄的application.properties
配置文件中設(shè)置靜態(tài)資源路徑,如下所示:
#設(shè)置靜態(tài)資源路徑
spring.resources.static-locations=classpath:static/,file:static/