springboot 本地上传一直没有问题,但是部署上服务器就总是报找不到路径问题 , 特此记录,以备后用。
首先 由于springboot 本地找到是本目录,到到服务器上由于没有权限在jar里写文件 只能在jar同级目录写文件
@Configuration
public class WebApiConfigurer implements WebMvcConfigurer {
//静态资源配置
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/view/**").addResourceLocations("file:"+System.getProperty("user.dir")+"/view/");
}
}
注 :
System.getProperty("user.dir") 不管是window 还是linux 都能获取相同的路径 解决了环境不同的问题 ;
@RequestMapping("/upload")
public void upload(@RequestParam("file") MultipartFile file) {
if (file.isEmpty()) {
throw new Exception();
}
String filePath = System.getProperty("user.dir");
File upload = new File(filePath + File.separator + "view" + File.separator);
if (!upload.exists()) {
upload.mkdirs();
}
File dest = new File(filePath + File.separator + "view" + File.separator + "index.html");
try {
file.transferTo(dest);
} catch (IOException e) {
log.error(e.getMessage(), e);
}
}
这样就可以了
这样就可以在服务器jar 同级目录view 下找到index文件