解决办法
(1)通过Spring Boot的配置参数“spring.servlet.multipart.location”明确指定上传文件的临时目录,确保该路径已经存在,而且该目录不会被操作系统清除。
spring.servlet.multipart.location=/data/tmp
将上传文件的临时目录指定到路径“/data/tmp”下。
实际上,在Spring Boot中关于上传文件的所有配置参数如下所示:
# MULTIPART (MultipartProperties) spring.servlet.multipart.enabled=true # Whether to enable support of multipart uploads. spring.servlet.multipart.file-size-threshold=0B # Threshold after which files are written to disk. spring.servlet.multipart.location= # Intermediate location of uploaded files. spring.servlet.multipart.max-file-size=1MB # Max file size. spring.servlet.multipart.max-request-size=10MB # Max request size. spring.servlet.multipart.resolve-lazily=false # Whether to resolve the multipart request lazily at the time of file or parameter access.
(2)在Spring容器中明确注册MultipartConfigElement对象,通过MultipartConfigFactory指定一个路径。
在上述源码追踪中就发现,Tomcat会使用MultipartConfigElement对象的location属性作为上传文件的临时目录。
/**
* 配置上传文件临时目录
* @return
*/@Beanpublic MultipartConfigElement multipartConfigElement() {
MultipartConfigFactory factory = new MultipartConfigFactory(); // tmp.dir参数在启动脚本中设置
String path = System.getProperty("tmp.dir"); if(path == null || "".equals(path.trim())) {
path = System.getProperty("user.dir");
}
String location = path + "/tmp";
File tmpFile = new File(location); // 如果临时目录不存在则创建
if (!tmpFile.exists()) {
tmpFile.mkdirs();
} // 明确指定上传文件的临时目录
factory.setLocation(location); return factory.createMultipartConfig();
}