添加启动配置类:在spring boot 中上传文件如果不指定临时文件路径,服务运行时间长了,操作系统会对默认的临时目录进行清理,导致再次上传文件时报错,找不到临时目录。
异常信息:
异常信息: org.springframework.web.multipart.MultipartException: Could not parse multipart servlet request;nested exception is java.io.IOException: The temporary upload location [/tmp/tomcat.1978174608501890996.8083/work/Tomcat/localhost/pmap] is not vali
以下是指定临时文件目录的方式:
- 第一种方式(spring boot 有配置入口)
spring: servlet: multipart: location: /home/uploadPath/temp
- 第二种方式在配置文件中添加:
location:
tempDir: /home/uploadPath/temp
添加启动配置类:
package com.sgcc.uap.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.MultipartConfigFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.servlet.MultipartConfigElement;
import java.io.File;
/**
* @ClassName MultipartConfig
* @Description 指定临时文件目录
* @Date 2022/10/25 9:14
*/
@Configuration
public class MultipartConfig {
@Value("${location.tempDir}")
private String tempDir;
@Bean
MultipartConfigElement mutipartConfigElement(){
MultipartConfigFactory factory = new MultipartConfigFactory();
File tmpDirFile = new File(tempDir);
// 判断文件夹是否存在
if (!tmpDirFile.exists()) {
tmpDirFile.mkdirs();
}
factory.setLocation(tempDir);
return factory.createMultipartConfig();
}
}