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/");  
    }


}
相关推荐
吴声子夜歌2 小时前
ApacheCommons——commons-pool2(高性能通用对象池框架)
java·开发语言·apache
mldong6 小时前
C# 开发者也有自己的轻量工作流引擎了:NuGet 装包,5 分钟跑通一条审批流
后端·c#·.net
xcl09257 小时前
幼儿托育系统开发实战:从需求分析到上线全流程指南
java·大数据·需求分析
吴声子夜歌7 小时前
ApacheCommons——commons-cli(命令行参数解析)
java·开发语言·apache
小小猪的春天8 小时前
Java 手写第一个 MCP Server:Spring AI MCP 半小时跑通
java·人工智能·spring boot·ai编程
find1star8 小时前
LeetCode 141:环形链表
java·算法·leetcode·链表
爱学堂IT分享8 小时前
鹤翔老师pmp项目管理培训认证考试课 (直播录播题库送学时证明)【共58课时】-51CTO学堂
后端
今天AI了吗8 小时前
DeepSeek Harness 深度解析:从评测架构到实战落地
java·网络·数据库·人工智能·架构·java-ee
王的宝库9 小时前
Go 项目结构:从单文件到标准工程布局
开发语言·后端·golang
许彰午9 小时前
27-AuthService登录链路
java·低代码·架构