spring boot对外部文件的访问

很多朋友都会遇到这个问题,项目打包成jar格式,本地其他盘符里面的文件访问不到(项目达成war包的和资源是在服务器访问的请忽视),这里只需要在配置文件中添加配置,然后使用建立一个WebMvcConfigurerAdapter拦截就可以了

(1) 首先 application.properties配置文件中添加如下配置

复制代码
#通过浏览器访问文件的路径
file.staticAccessPath=/api/file/**
#本地资源路径
file.uploadFolder=d:///uploadFile/
#file.uploadFolder=/root/laboratory/uploadfile/

(2) 然后新建一个配置类

复制代码
package com.xxx.xxx;

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.WebMvcConfigurationSupport;
//import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
public class UploadFilePathConfig extends WebMvcConfigurationSupport{

	@Value("${file.staticAccessPath}")
    private String staticAccessPath;
    @Value("${file.uploadFolder}")
    private String uploadFolder;
    
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
    	//外部文件
        registry.addResourceHandler(staticAccessPath).addResourceLocations("file:" + uploadFolder);
        
		//内部静态文件(使用WebMvcConfigurationSupport之后内部静态文件无法访问的话就添加以下这段代码)
		registry.addResourceHandler("/**")
        .addResourceLocations(ResourceUtils.CLASSPATH_URL_PREFIX+"/static/");  
    }


}
相关推荐
牛奔4 小时前
Go 如何打印调试深层或嵌套的结构体
开发语言·后端·golang
红烧大青虫5 小时前
HarmonyOS应用开发实战:小事记 - 数据迁移策略:RDB 表结构变更的版本号管理与 onUpgrade 回调
后端·华为·harmonyos·鸿蒙系统
geovindu5 小时前
go: Iterative Algorithms
开发语言·后端·算法·golang·迭代算法
阳光是sunny6 小时前
LangGraph实战教程:defer延迟节点——让收尾工作自动排到最后
前端·人工智能·后端
前端工作日常6 小时前
我学习到的Java中domain和dto区别
java·后端
kite01216 小时前
Go语言Map深度解析与最佳实践
开发语言·后端·golang
阳光是sunny7 小时前
LangGraph实战教程:控制流详解
前端·人工智能·后端
码农学院7 小时前
基于Spring Boot的跨境电商多语言订单管理系统架构设计
java·大数据·spring boot
技术小结-李爽8 小时前
【工具】pom文件的<packaging>
java·maven
hold?fish:palm8 小时前
kv存储主从复制的设计与实现
c++·redis·后端