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


}
相关推荐
Wang's Blog3 分钟前
Java 项目实战: 外卖平台优化-YApi接口管理平台与文档导入导出
java·开发语言·yapi
专业程序开发源8 分钟前
django新闻推荐系统70655-计算机课程设计、毕业设计
java·javascript·spring boot·后端·python·django·课程设计
打工仔折腾 AI20 分钟前
把 AI Agent 托管到家里电脑:UU远程端口映射与CLI实测记录
人工智能·后端·python·langchain·电脑·ai agent 实战
vx_Biye_Design24 分钟前
springboot一站式旅游管理平台81037-计算机课程设计、毕业设计
java·vue.js·spring boot·后端·课程设计·express·旅游
写后端的胖头鱼29 分钟前
时间复杂度 & 空间复杂度
java·数据结构·算法·时间复杂度·空间复杂度
嵌入式学习菌33 分钟前
ESP32 ModbusTCP 分片缓存
java·后端·spring
vx_Biye_Design34 分钟前
springboot宠物寄养服务预约与监管系统82684-计算机课程设计、毕业设计
java·vue.js·spring boot·elasticsearch·课程设计·express·宠物
程序员小杰@41 分钟前
Spring Boot 常用注解分类速记
java·spring boot·后端
挖掘狂人44 分钟前
Git 从 0 到 1:用一个小项目走完 add / commit / reset / merge / rebase / push
git·后端·github
vx_Biye_Design1 小时前
springboot小学生英语学习APP62773-计算机课程设计、毕业设计
java·vue.js·spring boot·后端·python·学习·课程设计