使用springboot 配置静态资源 小结 我总结了4种方式
静态资源访问方式配置
默认优先级
“classpath:/META‐INF/resources/”,
“classpath:/resources/”,
“classpath:/static/”,
“classpath:/public/”
“/”:当前项目的根路径
默认使用application.propertoes
第一种方式
spring.mvc.static-path-pattern=/**
##配置本地路径 (注意: 最后的/结尾一定要加)
file.path= /Users/huaxiansheng/IdeaProjects/project/p2ipxd/housev1.0/static/imgs/
##复写springboot 默认静态资源访问方式(注意: 最后的/结尾一定要加)
spring.resources.static-locations=classpath:/static/,classpath:/public/,classpath:/resources/,classpath:/META-INF/resources/,file:${file.path}
第二种方式
#本地文件目录
file.path=/Users/huaxiansheng/IdeaProjects/project/p2ipxd/housev1.0/static/imgs/
@Configuration
public class WebMvcConf extends WebMvcConfigurerAdapter {
@Value("${file.path}")
public String filePath;
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
// /* 是拦截所有的文件夹,不包含子文件夹
// /** 是拦截所有的文件夹及里面的子文件夹
registry.addResourceHandler("/**").addResourceLocations("file:"+filePath);
}
}
第三种方式 注意:springboot 打包不能打成jar 需要war 不太推荐
file.path=/static/imgs
//在文件上传的地方直接加入
String url = ResourceUtils.getURL("classpath:static").getPath();
File newFile = new File(url+filePath + "/" + Instant.now().getEpochSecond() + "/" + file.getOriginalFilename());
第四种方式(推荐方式)
#使用nginx 代理静态资源 文件目录随意放 配置server即可