springboot项目如何将本地资源路径映射成url路径

本文介绍了三种在Spring Boot项目中将本地磁盘资源映射为URL路径的方法,包括自定义WebMvcConfigurer实现类、继承WebMvcConfigurerAdapter(已过时)以及在application.yml配置文件中进行配置。通过这些方式,可以使用http://localhost:8080/image/s.jpg访问到D:/upload/s.jpg文件。

如何实现在项目中通过url路径访问本地磁盘的资源,将本地磁盘路径映射成虚拟路径

  • 方式一:自定义类实现WebMvcConfigurer接口,重写它的addResourceHandlers(ResourceHandlerRegistry registry)方法
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 FilePath implements WebMvcConfigurer {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
//   registry.addResourceHandler("虚拟路径").addResourceLocations("file:本地资源路径");
        registry.addResourceHandler("/image/**").addResourceLocations("file:D:/upload/");
    }
}

  • 方式二:跟方式一差不多,自定义类继承WebMvcConfigurerAdapter类,重写它的addResourceHandlers(ResourceHandlerRegistry registry)方法。但已经过时不推荐使用。
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@Configuration
public class FilePath2 extends WebMvcConfigurerAdapter {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        //   registry.addResourceHandler("虚拟路径").addResourceLocations("file:本地资源路径");
        registry.addResourceHandler("/image/**").addResourceLocations("file:D:/upload/");
    }
}
  • 方式三:在application.yml的配置文件进行配置
spring:
  mvc:
    static-path-pattern: '/image/**'
  resources:
    static-locations: 'file:D:/upload/'
总结:然后启动项目,可以通过http://localhost:8080/image/s.jpg,访问到本地磁盘的D:/upload/s.jpg文件。

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

评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

讨厌令狐冲

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

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

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

打赏作者

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

抵扣说明:

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

余额充值