SpringBoot静态资源映射的实现(实现WebMvcConfigurer方式)
- 新建WebMvcConfigurer类实现WebMvcConfigurer,重写addResourceHandlers方法
@Configuration
public class MyWebAppConfigurer implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
// linux使用
registry.addResourceHandler("static/**")
.addResourceLocations("file:/app/nas/");
// windows
registry.addResourceHandler("static/**")
.addResourceLocations("file:D:/picture/");
}
}
- 在访问资源文件的地址路径
例如:
https://web.com/web/static/app/nas/123.png
- https://web.com/ :域名
- web/:包名
- static/ :设置的addResourceHandler(“static/**”)
- app/nas/:设置的addResourceLocations(“file:/app/nas/”)
- 123.png:文件名
- 在具体存放资源文件的时候,文件都放在app/nas/下即可,当app/nas/下存在多级目录时,在文件名下带上多级目录即可。
- 还有一种利用配置文件实现资源映射的方式
# 默认值
spring.mvc.static-path-pattern=/**
# 默认值
spring.resources.static-locations=classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/
- spring.mvc.static-path-pattern:静态资源的加载起点(个人看法)。
- 与新建类方法相同,若写为/** ,则会覆盖系统默认路径,需在spring.resources.static-locations内重新添加路径才会起作用;
- 若修改为 /newPath/** ,则加载/resources/static/img/ajax.jpg,需要写为/newPath/img/ajax.jpg,修改前为/img/ajax.jpg。
-
spring.resources.static-locations:静态资源的默认加载路径。
添加新路径示例:
web.upload-path=d:/myfile/upload
web.front-path=d:/myfile/front
spring.resources.static-locations=file:${web.upload-path},file:${web.front-path}
- 通过配置文件实现资源映射的方式本人还没有使用过,仅作为参考。
- 上传文件的实现:
if(!file.isEmpty()){
// Windows
//String imgPath = "D:/web/img/";
// Linux
String imgPath = "/usr/local/img/";
// 上传的文件名
String imgName = file.getOriginalFilename();
File filepath = new File(imgPath,imgName);
// 判断路径是否存在,如果不存在就创建一个
if (!filepath.getParentFile().exists()) {
filepath.getParentFile().mkdirs();
}
// 将上传的文件保存到一个目标文件当中
file.transferTo(filepath);
}else {
System.out.println("图片上传失败!");
}
参考链接:Spring Boot静态资源映射(以图片上传并显示为例)