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


}
相关推荐
budingxiaomoli1 小时前
Spring IoC &DI
java·spring·ioc·di
Spider Cat 蜘蛛猫1 小时前
Springboot SSO系统设计文档
java·spring boot·后端
未若君雅裁2 小时前
MySQL高可用与扩展-主从复制读写分离分库分表
java·数据库·mysql
学习中.........2 小时前
从扰动函数的变化,感受红黑树带来的性能提升
java
计算机安禾2 小时前
【c++面向对象编程】第24篇:类型转换运算符:自定义隐式转换与explicit
java·c++·算法
zyk_computer3 小时前
AI 时代,或许 Rust 比 Python 更合适
人工智能·后端·python·ai·rust·ai编程·vibe coding
weixin199701080163 小时前
【保姆级教程】淘宝/天猫商品详情 API(item_get)接入指南:Python/Java/PHP 调用示例与 JSON 返回值解析
java·python·php
环流_3 小时前
redis核心数据类型在java中的操作
java·数据库·redis
雨辰AI3 小时前
SpringBoot3 项目国产化改造完整流程|从 MySQL 到人大金仓落地
java·数据库·后端·mysql·政务
带刺的坐椅3 小时前
Java 流程编排新范式 Solon Flow:一个引擎,七种节点,覆盖规则/任务/工作流/AI 编排全场景
java·spring·ai·solon·flow