springboot项目中大量用户上传的图片,不能放在jar中,这样每次重新部署项目的时候,图片就失效了,很是麻烦。
所以此时就需要自定义配置springboot的项目静态文件映射。
需要自定义映射规则:
有两种方法一种是基于配置文件,另一种是基于代码层面配置。
1 基于配置文件
#配置内部访问地址和外部图片访问地址
spring.mvc.static-path-pattern=/**
spring.resources.static-locations=file:D:/webapp/storage/files/img/,classpath:/static/
映射 /** 到本地磁盘路径下存放的图片,和tomcat中的图片路径
访问路径则是:
localhost:8080/jquery.min.js
localhost:8080/ 图片名
第一种方式没经过验证。
2 基于代码层面配置
@Configuration public class WebConfig implements WebMvcConfigurer { @Value("${upload.path:/web/files}") private String uploadPath; @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { // /home/file/**为前端URL访问路径 后面 file:xxxx为本地磁盘映射 registry.addResourceHandler("/file/**").addResourceLocations("file:C:" + uploadPath + "/"); } }
在使用代码进行配置时特别要注意映射到本地文件夹的路径结尾必须有分隔符“/"
访问外部文件的路径前要添加file:前缀,否则外部的资源访问不到