SpringBoot 读取项目中静态资源文件

该文介绍了如何在SpringBoot应用中配置FilePathConfig以设置静态资源路径,并通过WebMvcConfig实现对静态资源如/public/**和classpath:/public/的访问。同时,展示了如何映射文件系统中的资源,以及如何读取并获取项目中静态文件的磁盘路径。
摘要由CSDN通过智能技术生成

1. 允许静态资源被读取

  • 配置FilePathConfig

    @Data
    @NoArgsConstructor
    @Component
    @ConfigurationProperties(prefix="file.path")
    public class FilePathConfig {
        String absolute;
        String relative;
    ​
        public void setAbsolute(String absolute) {
            this.absolute = absolute;
            File fileDic = new File(absolute);
            if (!fileDic.exists()) {
                fileDic.mkdirs();
            }
        }
    }
  • 配置WebMvcConfig

    // 根据个人需求修改 "/public/**" 和 "classpath:/public/"
    @Configuration
    public class WebMvcConfig implements WebMvcConfigurer {
        @Resource
        FilePathConfig filePathConfig;
    ​
        @Override
        public void addResourceHandlers(ResourceHandlerRegistry registry) {
            registry.addResourceHandler("/public/**").addResourceLocations("classpath:/public/");
            //文件磁盘图片url 映射
            //配置server虚拟路径,handler为前台访问的目录,locations为files相对应的本地路径
            registry.addResourceHandler(filePathConfig.getRelative()+"/**").addResourceLocations("file:" + filePathConfig.getAbsolute());
        }
    }

2. 使用静态资源

String urlPath = "/public/test.txt";
ClassPathResource readFile = new ClassPathResource(urlPath);
File file = readFile.getFile();
String path = file.getPath(); // 获取到 项目中的 test.txt 在磁盘中的绝对路径

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值