The temporary upload location *** is not valid

spring boot项目在生产环境运行一段时间后,一次文件上传报如下异常:

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

原因:在linux系统中,spring boot应用服务每次使用java -jar启动后都会在/tmp目录下生成如下目录:

  1.  hsperfdata_root
  2. tomcat.************.9008(中间是一串数字,结尾是应用端口号)
  3. tomcat-docbase.*********.9008(中间是一串数字,结尾是应用端口号)

文件上传时会在tomcat.************.9008目录下创建临时文件,由于此目录在长时间没有使用会被系统清理掉,所以导致上传时出现上述异常。

解决办法:

  1. 临时解决办法:在服务器上创建异常中的目录(/tmp/tomcat.7333297176951596407.9008/work/Tomcat/localhost/***)
  2. 修改/tmp临时目录的清理规则,centos7设置方法如下,修改/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.*

     

  3. 代码修改临时文件的路径:
    @Configuration
    public class MultipartConfig {
    
        @Bean
        MultipartConfigElement multipartConfigElement() {
            MultipartConfigFactory factory = new MultipartConfigFactory();
            String location = System.getProperty("user.dir") + "/data/tmp";
            File tmpFile = new File(location);
            if (!tmpFile.exists()) {
                tmpFile.mkdirs();
            }
            factory.setLocation(location);
            return factory.createMultipartConfig();
        }
    }

     

  4. 在application的配置文件中增加如下内容:
    server.tomcat.basedir: /data/tmp

    欢迎同学留言,不足之处还望指正。

你可能感兴趣的:(Java)