行业知识
spring boot对外部文件的访问
2026-11-25 07:07:17
来源:互联网转载
���多朋友都会遇到这个问题,项目打包成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;@Configurationpublic 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/"); }}
下一篇:淘宝服务器爆满了怎么解决?