springboot前台页面访问某磁盘路径下的资源

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/xinyuebaihe/article/details/88199875

https://blog.csdn.net/qq_30447263/article/details/81085171

springboot前台页面访问某磁盘路径下的资源,直接访问不了,可以通过虚拟的方式,通过url方式访问。

package com.bootdo.x.config;

import com.bootdo.common.config.BootdoConfig;
import org.springframework.beans.factory.annotation.Autowired;
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 WebConfig implements WebMvcConfigurer {

    @Value("${bootdo.virtualPath}")
    private String virtualPath;

    @Value("${bootdo.uploadPath}")
    private String uploadPath;

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        //在F:/SpringBootFiles/Image/下如果有一张 Excalibar.jpg的图片,那么:
        //【1】访问:http://localhost:8080/imgs/Excalibar.jpg 可以访问到
        //【2】html 中 <img src="imgs/Excalibar.jpg">
        //registry.addResourceHandler("/img/m/**").addResourceLocations("file:E:/var/uploaded_files/");
        registry.addResourceHandler(virtualPath+"**").addResourceLocations("file:"+uploadPath);
    }

}

其实这个方式不太安全。如果是非常重要的文件,不想要别人随便访问。所以建议只访问静态资源。

如果一定要通过这种方式访问重要文件,其实也可以。只是要单独加拦截器。具体见:https://www.cnblogs.com/yangxiansen/p/7859991.html 。不知道能不能与shiro配全使用,使代码更简洁,还有待研究。

对于比较重要的文件,还是通过请求发送给controller进行处理,这样可以通过shiro用注解来直接设置权限。

猜你喜欢

转载自blog.csdn.net/xinyuebaihe/article/details/88199875