今天在使用应用上传文件时,发现文件上传不上去,一直卡在遮罩,后台查看日志报错如下:
Request processing failed; nested exception is org.springframework.web.multipart.MultipartException: Failed to parse multipart servlet request; nested exception is java.io.IOException: The temporary upload location [/opt/smil/smildatatemp] is not valid] with root cause java.io.IOException: The temporary upload location [/opt/anjiplus-smildataplat-uat/smildatatemp] is not valid
原因分析:
应用启动时会创建一个临时目录(linux) 在/tmp下,
注:windows是在C:\Users\用户名\AppData\Local\Temp下
linux默认10天会清理没有变动的临时文件,也就是如果我们的应用超过10天没有使用上传文件的功能,linux系统会清除掉临时目录,导致我们上传文件时因为找不到临时目录报io异常.同理,如果是windows下出现这个异常,是因为删除了tomcat临时文件目录,解决方法:
1 重启应用即可(不推荐)
2 添加配置类(推荐)
import org.springframework.beans.factory.annotation.Autowired;
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;
/**
* \* Date: 2020/4/29
* \*
* \* Desc:
*/
@Configuration
public class MultipartConfig {
//读取application.properties的配置类
@Autowired
private PropertiesConfig propertiesConfig;
@Bean
MultipartConfigElement multipartConfigElement() {
String tempFilePath = propertiesConfig.getFile_temp_dir();// /spingboot/uploaddir/temp
MultipartConfigFactory factory = new MultipartConfigFactory();
File tempFile = new File(tempFilePath);
if (!tempFile.exists()) {
tempFile.mkdirs();
}
factory.setLocation(tempFilePath);
return factory.createMultipartConfig();
}
}
上面配置类会创建临时目录文件夹,并且以此文件夹/spingboot/uploaddir/temp作为临时文件目录,不会因常时间没有变动而被linux系统所清理