一 前言:
每个系统中,上传图片是必备可少的。而且也是常用的功能。但是SpringBoot项目,打包生成jar包,部署到docker中, 上传文件的路径,就需要大家特别注意。相信做个功能的小伙伴,遇到了这个坑。
二 文件上传的解决方案
方案一: OSS对象存储 需要买存储服务器,对接SDK,费用成本大,小项目没有必要
方案二: 直接上传到服务器上面,替换OSS对象存储的方案,费用成本小,适合小型的项目.
我这里说的是第二种方案;
解决步骤:
第一步:
在application.properties或者 yml 中设置存储的地址
比如
spring.thymeleaf.suffix=.html
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.mode=HTML5
spring.thymeleaf.cache=false
spring.mvc.static-path-pattern=/static/**/
#centos服务器文件地址
exam.upload.path=/usr/local/exam/upload
#window版本文件地址
exam.upload.path=D:\\xxx\\exam\\exam\\src\\main\\resources\\static\\upload
第二步: 添加静态资源放行
@Configuration
public class MyPicConfig implements WebMvcConfigurer{
//上传地址
@Value("${exam.upload.path}")
private String filePath;
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
String os = System.getProperty("os.name");
if (os.toLowerCase().startsWith("win")) {
//如果是Windows系统
registry.addResourceHandler("/static/upload/**")
.addResourceLocations("file:"+filePath);
} else {
//linux 和mac
registry.addResourceHandler(