在没打包之前我都把用户上传文件保存在classpath路径下的静态文件夹里
path = new File(ResourceUtils.getURL("classpath:").getPath());
File upload = new File(path.getAbsolutePath(), "static/images/goods/");
String uploadPath = upload + File.separator;
filename.transferTo(new File( uploadPath+id+".png"));
这样做在打包之后上传功能就会报异常class path resource [] cannot be resolved to URL because it does not exist
因为打包成jar之后你还向classpath上传文件是不可以的,因为无法对jar进行写入
我的解决办法是做一个自定义静态资源映射,只需要在配置文件中添加自己想要映射的路径即可,我考虑到windows下和Linux下的不同配置了两个
#Windows下的上传静态资源路径
windows.upload.path=D:/uploads/
#linux下的上传静态资源文件路径
linux.upload.path=/uploads/
spring.mvc.static-path-pattern=/**
spring.resources.static-locations=classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/,file:${windows.upload.path},file:${linux.upload.path}
在存储用户上传文件的控制器中
//引入配置文件中自定义的映射路径
@Value("${windows.upload.path}")
private String windowsUploadPath;
@Value("${linux.upload.path}")
private String linuxUploadPath;
//方法中
//判断系统类型
if (JudgeSystem.isLinux()){
path = new File(linuxUploadPath);
upload = new File(path.getAbsolutePath(), "/images/goods/");
}else if (JudgeSystem.isWindows()){
path = new File(windowsUploadPath);
upload = new File(path.getAbsolutePath(), "/images/goods/");
}
if (null==upload){
return reqeustStart.build(500,"上传失败");
}
if (!upload.exists()) upload.mkdirs();
//添加分隔符
String uploadPath = upload + File.separator;
filename.transferTo(new File( uploadPath+id+".png"));
访问映射的资源URL为,不需要添uploads