靜態資源路徑是指系統可以直接訪問的路徑,且路徑下的所有文件均可被用戶直接讀取。
在Springboot中默認的靜態資源路徑有:classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/,從這里可以看出這里的靜態資源路徑都是在classpath中(也就是在項目路徑下指定的這幾個文件夾)
試想這樣一種情況:一個網站有文件上傳文件的功能,如果被上傳的文件放在上述的那些文件夾中會有怎樣的后果?
- 網站數據與程序代碼不能有效分離;
- 當項目被打包成一個
.jar文件部署時,再將上傳的文件放到這個.jar文件中是有多么低的效率; - 網站數據的備份將會很痛苦。
此時可能最佳的解決辦法是將靜態資源路徑設置到磁盤的基本個目錄。
在Springboot中可以直接在配置文件中覆蓋默認的靜態資源路徑的配置信息:
application.properties配置文件如下:
server.port=1122 web.upload-path=D:/temp/study13/ spring.mvc.static-path-pattern=/** spring.resources.static-locations=classpath:/META-INF/resources/,classpath:/resources/,\ classpath:/static/,classpath:/public/,file:${web.upload-path}
注意:web.upload-path這個屬於自定義的屬性,指定了一個路徑,注意要以/結尾;
spring.mvc.static-path-pattern=/**表示所有的訪問都經過靜態資源路徑;
spring.resources.static-locations在這里配置靜態資源路徑,前面說了這里的配置是覆蓋默認配置,所以需要將默認的也加上否則static、public等這些路徑將不能被當作靜態資源路徑,在這個最末尾的file:${web.upload-path}之所有要加file:是因為指定的是一個具體的硬盤路徑,其他的使用classpath指的是系統環境變量
- 編寫測試類上傳文件
package com.zslin; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.util.FileCopyUtils; import java.io.File; /** * Created by 鍾述林 393156105@qq.com on 2016/10/24 0:44. */ @SpringBootTest @RunWith(SpringRunner.class) public class FileTest { @Value("${web.upload-path}") private String path; /** 文件上傳測試 */ @Test public void uploadTest() throws Exception { File f = new File("D:/pic.jpg"); FileCopyUtils.copy(f, new File(path+"/1.jpg")); } }
注意:這里將D:/pic.jpg上傳到配置的靜態資源路徑下,下面再寫一個測試方法來遍歷此路徑下的所有文件。
@Test public void listFilesTest() { File file = new File(path); for(File f : file.listFiles()) { System.out.println("fileName : "+f.getName()); } }
可以到得結果:
fileName : 1.jpg
說明文件已上傳成功,靜態資源路徑也配置成功。
- 瀏覽器方式驗證
由於前面已經在靜態資源路徑中上傳了一個名為1.jpg的圖片,也使用server.port=1122設置了端口號為1122,所以可以通過瀏覽器打開:http://localhost:1122/1.jpg訪問到剛剛上傳的圖片。
示例代碼:https://github.com/zsl131/spring-boot-test/tree/master/study13
本文章來自【知識林】
