springboot項目中大量用戶上傳的圖片,不能放在jar中,這樣每次重新部署項目的時候,圖片就失效了,很是麻煩。
所以此時就需要自定義配置springboot的項目靜態文件映射。
需要自定義映射規則:
有兩種方法一種是基於配置文件,另一種是基於代碼層面配置。
1 基於配置文件
#配置內部訪問地址和外部圖片訪問地址
spring.mvc.static-path-pattern=/**
spring.resources.static-locations=file:D:/webapp/storage/files/img/,classpath:/static/
映射 /** 到本地磁盤路徑下存放的圖片,和tomcat中的圖片路徑
訪問路徑則是:
localhost:8080/jquery.min.js
localhost:8080/ 圖片名
第一種方式沒經過驗證。
2 基於代碼層面配置
@Configuration public class WebConfig implements WebMvcConfigurer { @Value("${upload.path:/web/files}") private String uploadPath; @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { // /home/file/**為前端URL訪問路徑 后面 file:xxxx為本地磁盤映射 registry.addResourceHandler("/file/**").addResourceLocations("file:C:" + uploadPath + "/"); } }
在使用代碼進行配置時特別要注意映射到本地文件夾的路徑結尾必須有分隔符“/"
訪問外部文件的路徑前要添加file:前綴,否則外部的資源訪問不到