一个长久没更新过的spring boot项目突然间文件上传错误,异常信息如下,此原因主要问题是tomcat默认的临时目录没了,项目运行的服务器每隔一段时间会清除 /tmp 临时目录,项目每次启动都会创建临时目录,经常重启的项目不会有此问题。
解决方案:
1. 重启项目,每隔一段时间重启,可以跟 /tmp 清除周期保持一致
2. 重启项目,在启动的时候增加参数-Djava.io.tmpdir=自定义临时路径:
java -Djava.io.tmpdir=tempDirPath -jar xxxx.jar
自定义临时路径不在 /tmp 默认是不会被系统删除的
3. 修改spring boot 配置文件
server:
tomcat:
basedir: tempDirPath
4. 修改代码
@Configuration public class MultipartConfig { @Bean MultipartConfigElement multipartConfigElement() { MultipartConfigFactory factory = new MultipartConfigFactory(); String location = "自定义临时目录"; File tmpFile = new File(location); if (!tmpFile.exists()) { tmpFile.mkdirs(); } factory.setLocation(location); return factory.createMultipartConfig(); } }
部分异常信息:
1 The temporary upload location [/tmp/tomcat/work/Tomcat/localhost/ROOT] is not valid] with root cause 2 3 java.io.IOException: The temporary upload location [/tmp/tomcat.2059369046991191352.8764/work/Tomcat/localhost/ROOT] is not valid 4