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


}
相关推荐
mldong5 小时前
工作流引擎的灵魂:状态机与 submitType
后端
朦胧之8 小时前
Go 基础
后端·go
码农颜8 小时前
5.4.1 锁分类
java·数据库·mysql
lun8 小时前
Agent 工具调用成长史:理清楚 Function Calling、MCP、CLI 的关系
后端
Python私教8 小时前
Codex 自动写 Commit 够安全吗?一套证据化 Git 提交流程
人工智能·git·后端
Python私教8 小时前
AI Agent 上生产要不要开写权限?我把执行链拆成 4 道闸门
人工智能·后端·python
lun8 小时前
Claude Code 多 Agent 实现:subAgent & Agent Teams
后端
linux-hzh9 小时前
百日算法修炼 · Day 03
java·算法
不负岁月无痕10 小时前
简单理解操作系统结构
java·linux·c语言·开发语言·c++·面试
mister_guo10 小时前
Java线程池参数应该如何设置(ThreadPoolExecutor)
java