前端页面通过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>