SpringBoot前端通過 URL訪問本地磁盤文件,其實就是 SpringBoot訪問web中的靜態資源的處理方式。
SpringBoot 訪問web中的靜態資源:https://blog.csdn.net/qq_42402854/article/details/90295079
首先,我們知道瀏覽器訪問本地磁盤文件的方式為:
在瀏覽器直接輸入:
file:///+本地磁盤目錄或者磁盤文件全路徑
我們只需要在 Spring Boot中配置靜態資源的處理即可。
1、自定義配置類
將配置信息提取到配置文件,方便我們配置。
application.yml配置文件:自定義 file配置信息
# 文件上傳相關
file:bucketName: def_bucketlocal:enable: true
# base-path: /home/app/ws_demo/ws-filesbase-path: D:/ws-files/uploadbaseUrl: http://127.0.0.1:19090/ws/profile
自定義 file配置類:
@Data
@Component
@ConfigurationProperties(prefix = "file")
public class FileProperties {/*** 默認的存儲桶名稱*/private String bucketName = "bucketName";/*** 本地文件配置信息*/private LocalFileProperties local;}
/*** 本地文件 配置信息*/
@Data
@Component
@ConfigurationProperties(prefix = "local")
public class LocalFileProperties {/*** 是否開啟*/private boolean enable;/*** 默認磁盤根路徑*/private String basePath;/*** 默認文件URL前綴*/private String baseUrl;}
2、添加靜態資源映射
在配置類中添加靜態資源映射。
/*** WebMvc 配置類*/
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {@Autowiredprivate FileProperties fileProperties;/*** 配置靜態資源訪問映射** @param registry*/@Overridepublic void addResourceHandlers(ResourceHandlerRegistry registry) {registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");// swagger-bootstrap-ui依賴registry.addResourceHandler("doc.html").addResourceLocations("classpath:/META-INF/resources/");//本地文件上傳路徑registry.addResourceHandler("/profile/**") // 自定義URL訪問前綴,和file配置一致.addResourceLocations(String.format("%s/%s/", "file:", fileProperties.getLocal().getBasePath()));}}
3、前端通過 URL訪問
本地文件:
啟動項目,瀏覽器訪問 URL接口。
– 求知若饑,虛心若愚。