前端頁面通過URL訪問本地文件夾
因爲SpringBoot項目中使用的嵌入Tomcat,所以前端頁面不能像以前那樣直接將從Tomcat很目錄訪問文件。
解決辦法:繼承WebMvcConfigurer接口對訪問URL進行攔截,然後將訪問文件的URL映射至本地文件夾
在application.yml中添加配置
首先在本地創建文件夾
accessFile:
resourceHandler: /show/** #匹配需要攔截的URL
location: E:/tomcat/virtical/ #本地文件夾
實現WebMvcConfigurer接口
對匹配的URL進行攔截,映射至本地文件夾
package rui.zhang.springboot1.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class MyWebMVCConfig implements WebMvcConfigurer {
@Value("${accessFile.resourceHandler}")
private String resourceHandler; //匹配url 中的資源映射
@Value("${accessFile.location}")
private String location; //上傳文件保存的本地目錄
/**
* 配置靜態資源映射
*
* @param registry
*/
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
//匹配到resourceHandler,將URL映射至location,也就是本地文件夾
registry.addResourceHandler(resourceHandler).addResourceLocations("file:///" + location);
}
}
前端頁面中進行訪問
src對應的URL地址就會被映射到本地的文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>home</title>
</head>
<body>
<img src="show/my.jpg" width="30px" height="30px"/>
<video src="show/vv.mp4" controls="controls">
</video>
</body>
</html>