Skip to content

Spring Boot项目启动长时间后,无法上传文件的问题解决方法

GeXiangDong edited this page Feb 12, 2019 · 4 revisions

Spring boot项目启动过一段较长时间后,在使用上传文件相关功能时,会出现错误。错误信息和下面的类似,临时目录不存在了

Could not parse multipart servlet request; nested exception is java.io.IOException: The temporary upload location [/tmp/tomcat.7313397276953595407.8090/work/Tomcat/localhost/ROOT] is not valid。

Could not parse multipart servlet request; nested exception is java.io.IOException: The temporary upload location [C:\Users\Administrator\AppData\Local\Temp\tomcat.7174298170552445669.8002\work\Tomcat\localhost\server] is not valid

这是由于tomcat默认使用的临时目录是在系统临时目录下创建的,而系统临时目录被系统清理了,删除了tomcat的临时目录。

知道原因后解决办法也就有了:把tomcat的临时目录设置到一个固定的不会被清理的目录下。

@Configuration
public class MultipartConfig {

    @Bean
    MultipartConfigElement multipartConfigElement() {
        MultipartConfigFactory factory = new MultipartConfigFactory();
        String tempLocation = "c:\\temp";
        File tmpFile = new File(tempLocation);
        if (!tmpFile.exists()) {
            tmpFile.mkdirs();
        }
        factory.setLocation(tempLocation);
        return factory.createMultipartConfig();
    }
}