Spring Boot Tomcat temporary directory tmp throws an error exception

First of all, we should know that for http POST requests, it needs to use this temporary directory to store post data.
Secondly, because the directory is a temporary file hanging to the /temp directory, then for some OS systems, such as centOS will often delete this temporary directory, so that the directory does not exist anymore.

solution

1. application.ymlSet in the file multipart locationand restart the project

spring:
  http:
    multipart:
      location: /data/upload_tmp

2. application.ymlSet in the file

server
  tomcat:
     basedir: /tmp/tomcat

3. Add in the configuration filebean

@Bean
public MultipartConfigElement multipartConfigElement() {
    
    
  MultipartConfigFactory factory = new MultipartConfigFactory();
  factory.setLocation("/tmp/tomcat");
  return factory.createMultipartConfig();
}

4. Add startup parameters -java.tmp.dir=/path/to/application/temp/and restart.

The above are all refer to Ruoyi's official website, but there is a drawback, abnormal files cannot be deleted in the temporary directory , so I used the following method.

5.TomcatEmbeddedServletContainerFactory.setBaseDirectory(file);

@Configuration
public class TomcatConfig {
    
    
    private static final Log LOG = LogFactory.get();

    @Bean
    public TomcatEmbeddedServletContainerFactory servletContainer() {
    
    
        TomcatEmbeddedServletContainerFactory factory = new MyTomcatEmbeddedServletContainerFactory();
        // 服务上下文配置
        // factory.setContextPath("/test");
        setBaseDirAndClean(factory);
        return factory;
    }

    // 指定内置tomcat的工作目录
    private void setBaseDirAndClean(
            TomcatEmbeddedServletContainerFactory factory) {
    
    
        File file = new File("./tomcat/laker/tmp");
        try {
    
    
            if (FileUtil.exist(file)) {
    
    
                List<File> files = FileUtil.loopFiles(file);
                if (CollUtil.isNotEmpty(files)) {
    
    
                    for (File delfile : files) {
    
    
                        delfile.delete();
                    }
                }
            } else {
    
    
                FileUtil.mkdir(file);
            }
        } catch (IORuntimeException e) {
    
    
            LOG.error(e);
        }
        factory.setBaseDirectory(file);
    }
}

reference:

  • https://doc.ruoyi.vip/ruoyi/other/faq.html#tomcat%E4%B8%B4%E6%97%B6%E7%9B%AE%E5%BD%95tmp%E6%8A%9B%E9%94%99%E8%AF%AF%E5%BC%82%E5%B8%B8

Guess you like

Origin blog.csdn.net/abu935009066/article/details/114596193