1、配置WebMvcConfigurationSupport2、配置下载路径3、测试
在非分布式集群环境下,我们放了方便可以不进行nginx配置,也不需要写额外的接口就可以实现文件的访问与下载处理,具体实现通过
WebMvcConfigurationSupport的
addResourceHandlers方法进行实现;
创建WebMvcRegistrationsConfig类继承WebMvcConfigurationSupport类,并且重新addResourceHandlers方法,如果配置了拦截器那么需要进行放行处理,代码如下:
@Configuration
public class WebMvcRegistrationsConfig extends WebMvcConfigurationSupport {
private final String fileRootPath = "D:\file";
@Resource
private HandlerInterceptor interceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
// 无需拦截的接口集合
List ignorePath = new ArrayList<>();
// 文件静态资源访问
ignorePath.add("/source/**");
registry.addInterceptor(interceptor).addPathPatterns("/**").excludePathPatterns(ignorePath);
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
// 文件静态资源虚拟路径,`source`为任意名称即可
registry.addResourceHandler("/source/**").addResourceLocations("file:" + fileRootPath + "/source/");
}
}
2、配置下载路径
在WebMvcRegistrationsConfig中,配置的静态文件路径为D:\file\source,所以只要文件在D:\file\source路径下,就可以完成文件的下载,比如文件情况如下:
test.txt文件内容如下:
假设SpringBoot服务的端口为9999,context-path为demo:
server:
port: 9999
servlet:
context-path: /demo
那么访问test.txt的地址就是:http://localhost:9999/demo/source/test.txt
效果:



