springboot Temporary File Storage Directory Configuration

  • 2021-10-15 10:36:46
  • OfStack

springboot Temporary File Storage Directory Configuration

Scenario:

Upload the file function to report errors, and then check the log.

Error log:

The temporary upload location [/tmp/tomcat.7957874575370093230.8088/work/Tomcat/localhost/ROOT] is not valid

Reason:

In the linux system, when the springboot application service is restarted (java-jar command starts the service), a file directory of tomcat* will be generated under the /tmp directory of the operating system, and the uploaded files should be converted into temporary files and saved under this folder.

Due to temporary/tmp directory files, in the long time (10 days) without use, will be automatically deleted by the system mechanism. Therefore, if the system does not use the temporary folder for a long time, it may cause the above problem.

Solution:

1. Create a temporary folder:


mkdir -p /tmp/tomcat.7957874575370093230.8088/work/Tomcat/localhost/ROOT

This may happen later

2. application. properties reconfigure 1 file directory and restart the project


#  Storage Tomcat The log of, Dump Temporary folder for files such as, default to the system's tmp Folder 
server.tomcat.basedir=/data/apps/temp

3. The configuration class configures the temporary file storage directory


    @Bean
    MultipartConfigElement multipartConfigElement() {
        MultipartConfigFactory factory = new MultipartConfigFactory();
        factory.setLocation(tmepPath);
        return factory.createMultipartConfig();
    }

Springboot Modify the storage location of temporary files

Report an error

After the project has been running online for 1 period of time, the following exception is thrown when uploading files:

The temporary upload location [/tmp/tomcat.*.80/work/Tomcat/localhost/ROOT] is not valid

After searching, the following solution was adopted: "Modify the location of temporary files."

Add in the application. yml file


location:
  tempDir: /opt/location/tempDir # Here is *unix System-related location of 

To add a configuration class to a project


@Configuration
public class MultipartConfig {
   @Value("${location.tempDir:/opt/tempDir}")
   private String tempDir;

   @Bean
   MultipartConfigElement multipartConfigElement() {
      MultipartConfigFactory factory = new MultipartConfigFactory();
      File tmpDirFile = new File(tempDir);
      //  Determine if a folder exists 
      if (!tmpDirFile.exists()) {
         tmpDirFile.mkdirs();
      }
      factory.setLocation(tempDir);
      return factory.createMultipartConfig();
   }
}

Related articles: