靜態資源路徑是指系統可以直接訪問的路徑,且路徑下的所有文件均可被用戶直接讀取。
在Springboot中默認的靜態資源路徑有:classpath:/META-INF/resources/
,classpath:/resources/
,classpath:/static/
,classpath:/public/
,從這里可以看出這里的靜態資源路徑都是在classpath
中(也就是在項目路徑下指定的這幾個文件夾)
試想這樣一種情況:一個網站有文件上傳文件的功能,如果被上傳的文件放在上述的那些文件夾中會有怎樣的后果?
- 網站數據與程序代碼不能有效分離;
- 當項目被打包成一個
.jar
文件部署時,再將上傳的文件放到這個.jar
文件中是有多么低的效率; - 網站數據的備份將會很痛苦。
此時可能最佳的解決辦法是將靜態資源路徑設置到磁盤的基本個目錄。
在Springboot中可以直接在配置文件中覆蓋默認的靜態資源路徑的配置信息:
application.properties
配置文件如下:
web.upload-path=E:/jsr_img/
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
指定的是系統環境變量;
圖片上傳和訪問例子:
上傳圖片:
public int insertImg(MultipartFile file) { String filename = file.getOriginalFilename();//上傳圖片的名字 String suffixName = filename.substring(filename.lastIndexOf(".")); String name = UUID.randomUUID().toString(); filename = name + suffixName;//圖片重命名 String imgFilePath = "E:/jsr_img/"; String path_img = imgFilePath + filename;//圖片存儲路徑 //第一次如果沒有保存圖片的文件夾創建文件夾 File dest = new File(path_img); if (!dest.getParentFile().exists()) { dest.getParentFile().mkdirs(); } //將上傳文件存儲到服務器中 try { file.transferTo(dest); } catch (IOException e) { e.printStackTrace(); } //圖片路徑存儲到數據庫 VideoImgEntity videoImgEntity=new VideoImgEntity(); videoImgEntity.setImgPath(filename); }
訪問圖片:
http://localhost:端口號/數據庫中的圖片路徑
其他配置文件:
spring.http.multipart.enabled=true #默認支持文件上傳.
spring.http.multipart.file-size-threshold=0 #支持文件寫入磁盤.
spring.http.multipart.location= # 上傳文件的臨時目錄
spring.http.multipart.max-file-size=1Mb # 最大支持文件大小
spring.http.multipart.max-request-size=10Mb # 最大支持請求大小