java.io.IOException: The temporary upload location [/tmp/tomcat.xxx.xxx/work/Tomcat/localhost/ROOT] is not valid

报错原因 

  • 临时文件夹无效

在Spring Boot项目启动后,系统会在‘/tmp’目录下自动的创建几个目录:

tomcat.************.8088
tomcat-docbase.*********.8088

Multipart(form-data)的方式处理请求时,默认就是在第二个目录下创建临时文件的。

  • 程序对文件的操作时:会生成临时文件,暂存在临时文件中;Linux系统的tmpwatch 命令会删除10天未使用的临时文件;长时间不进行上传操作,导致/tmp下面的tomcat临时文件目录被删除,且删除的文件不可恢复,上传文件时获取不到文件目录,导致报错。

解决方法

  • 方案1 修改tomcat启动配置 添加-Djava.io.tmpdir=
  • 方案2 
//1.该处也需要配置下
@SpringBootApplication(exclude = {MultipartAutoConfiguration.class})
public class TestApplication {

    public static void main(String[] args) {
        SpringApplication.run(TestApplication .class, args);
    }

    /**
     * 解决文件上传,临时文件夹被程序自动删除问题
     *
     * 文件上传时自定义临时路径
     * @return
     */
    @Bean
    MultipartConfigElement multipartConfigElement() {
        MultipartConfigFactory factory = new MultipartConfigFactory();
        //2.该处就是指定的路径(需要提前创建好目录,否则上传时会抛出异常)
        factory.setLocation("/data/uploadtmp");
        return factory.createMultipartConfig();
    }
}
  • 方案三 

  CentOS6以下系统(含)使用watchtmp + cron来实现定时清理临时文件的效果,这点在CentOS7发生了变化,在CentOS7下,系统使用systemd管理易变与临时文件,与之相关的系统服务有3个:

systemd-tmpfiles-setup.service  :Create Volatile Files and Directories
systemd-tmpfiles-setup-dev.service:Create static device nodes in /dev
systemd-tmpfiles-clean.service :Cleanup of Temporary Directories

  相关的配置文件也有3个地方:

/etc/tmpfiles.d/*.conf
/run/tmpfiles.d/*.conf
/usr/lib/tmpfiles.d/*.conf

  /tmp目录的清理规则主要取决于/usr/lib/tmpfiles.d/tmp.conf文件的设定,默认的配置内容为:

#  This file is part of systemd.
#
#  systemd is free software; you can redistribute it and/or modify it
#  under the terms of the GNU Lesser General Public License as published by
#  the Free Software Foundation; either version 2.1 of the License, or
#  (at your option) any later version.

# See tmpfiles.d(5) for details

# Clear tmp directories separately, to make them easier to override
v /tmp 1777 root root 10d           #   清理/tmp下10天前的目录和文件
v /var/tmp 1777 root root 30d       #   清理/var/tmp下30天前的目录和文件

# Exclude namespace mountpoints created with PrivateTmp=yes
x /tmp/systemd-private-%b-*
X /tmp/systemd-private-%b-*/tmp
x /var/tmp/systemd-private-%b-*
X /var/tmp/systemd-private-%b-*/tmp

  我们可以配置这个文件,比如你不想让系统自动清理/tmp下以tomcat开头的目录,那么增加下面这条内容到配置文件中即可:

  

x /tmp/tomcat.*

更多配置内容参考:tmpfiles.d 中文手册

原文地址:https://www.cnblogs.com/mrelk/p/11230040.html