springboot重写适配器addResourceHandler

目的:
把上传至服务器指定物理磁盘相关目录(绝对路径)的文件通过浏览器直接访问预览。
这种具体实现其实是要配置一个映射关系的,即配置一个虚拟路径来映射文件的真实绝对路径(完美的隐藏了文件的真实物理路径,可以说不但很安全,而且外网可以直接访问)。

@Override
protected void addResourceHandlers(ResourceHandlerRegistry registry) {
    String os = System.getProperty("os.name");

    //如果是Windows系统
    if (os.toLowerCase().startsWith("win")) {
        registry.addResourceHandler("/app_file/**")
                // /app_file/**表示在磁盘filePathWindow目录下的所有资源会被解析为以下的路径
                .addResourceLocations("file:" + filePathWindow);
    } else {  //linux 和mac
        registry.addResourceHandler("/app_file/**")
                .addResourceLocations("file:" + filePathLinux) ;
    }
    super.addResourceHandlers(registry);
}

在这里插入图片描述
在这里插入图片描述



注:

  1. 编写类继承WebMvcConfigurerAdapter类,重写该类的addResourceHandlers方法;其中addResourceHandler指向映射路径,addResourceLocations指向资源文件路径;资源文件路径地址必须以/结尾,指向文件目录上一层
  2. 还可以在addResourceHandlers方法中写多套映射策略
class WebConfigurer extends WebMvcConfigurerAdapter {
	@Autowired
	BootdoConfig bootdoConfig;
	@Override
	public void addResourceHandlers(ResourceHandlerRegistry registry) {
		//图片资源
		registry.addResourceHandler("/files/**").addResourceLocations("file:///"+"/Users/fanzhen/Documents/ideaworkspaces/bootdo/bootdo/uploaded_files/");
		//文档资源
		registry.addResourceHandler("/docs/**").addResourceLocations("file:///"+"/Users/fanzhen/Documents/ideaworkspaces/bootdo/bootdo/uploaded_files/docs/");
		super.addResourceHandlers(registry);
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

hvk_l

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值