File upload error Failed to parse multipart servlet request

Error message:

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

It shows that [/tmp/tomcat.1428942566812653608.8090/work/Tomcat/localhost/ROOT] cannot be found.

The reason is that
when I upload the file, the system prompts an error, because centos has automatic cleaning rules for temporary files. If it is not used for a long time (10 days by default), this directory will be cleaned up, which will lead to our above problems. causing the upload to fail.
​Analysis
:

  1. First of all, we should know that for http POST requests, it needs to use this temporary directory to store post data.

  2. Secondly, because this directory is a temporary file hung under the /temp directory, then for some OS systems, such as centOS, this temporary directory will often be deleted, so the directory does not exist.

Verify whether this is the reason:
first enter the server to see if this directory exists

solution

  1. Restart the project, but the problem cannot be solved from the root cause. If it is not used for a long time (the time is cleaned up according to the rules defined by centos), this problem will still occur after being cleaned up.
  2. Modify the application.yml configuration file
    The first type:
spring:
    # 文件上传
  servlet:
     multipart:
       # 单个文件大小
       max-file-size:  10MB
       # 设置总上传的文件大小
       max-request-size:  20MB
       # 上传文件的中间位置
       location: /alited/uploadPath

the second

server:
   tomcat:
   		#设定tomcat的basedir目录,如果没有指定则使用临时目录
      basedir: /home/app/tomcat_upload_temp

Of course, this directory must exist here.

Failed to parse multipart servlet request; nested exception is java.io.IOException: The temporary upload location [D:\alited\uploadPath\tmp] is not valid

If it does not exist, the above error will still be reported, but the path has changed, so you can add a configuration under the startup class to automatically create the directory.

public class StartApplication
{
    
    
    @Value("${spring.servlet.multipart.location}")
    private  String tempDir;

    public static void main(String[] args)
    {
    
    
        System.setProperty("spring.devtools.restart.enabled", "false");
        SpringApplication.run(StartApplication.class, args);
    }

    /**
     * 配置用来自动创建目录用来指定上传中间目录
     */
    @Bean("mkdir")
    public void mkDir(){
    
    
        File file = new File(tempDir);
        // 判断文件夹是否存在
        if (!file.exists()){
    
    
             //创建文件夹
            file.mkdirs(); 
        }
    }
}

Guess you like

Origin blog.csdn.net/qq_41596778/article/details/128866132