SpringBoot项目中前端页面通过URL访问本地文件夹(访问静态文件)

前端页面通过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>
  • 7
    点赞
  • 36
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值