SpringBoot:文件上传失败Could not parse multipart servlet request

一、问题的描述

SpringBoot框架的项目,启动后文件上传没问题。一段时间后突然发现上传文件失败,提示如下错误:

org.springframework.web.multipart.MultipartException: Failed to parse multipart servlet request; 

nested exception is java.io.IOException: 

The temporary upload location [/tmp/tomcat.2348860723697381820.8888/work/Tomcat/localhost/sdnplatform#ipt] is not valid

二、问题的分析

SpringBoot启动时会创建一个/tmp/tomcat.*/work/Tomcat/localhost/*的临时目录作为文件上传的临时目录,用于缓存,但是该目录会在n天之后被系统自动清理掉,这个清理是由linux操作系统完成的,具体的配置如下 vim /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
v /var/tmp 1777 root root 30d

# 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

三、问题的解决方案

  1. 重启项目
  2. 增加服务配置,自定义baseDir
server.tomcat.basedir=/tmp/tomcat
  1. 注入bean,手动配置临时目录
@Bean
MultipartConfigElement multipartConfigElement() {
    MultipartConfigFactory factory = new MultipartConfigFactory();
    factory.setLocation("/tmp/tomcat");
    
    return factory.createMultipartConfig();
}
  1. 配置服务器不删除tmp目录下的tomcat
vim /usr/lib/tmpfiles.d/tmp.conf

# 添加一行
x /tmp/tomcat.*

你可能感兴趣的:(后端框架之Struts,Spring,SpringBoot)