解决Spring Boot应用上传文件时报错“spring.servlet.multipart.location”的方法?相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。
解决办法
(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();
}看完上述内容,你们掌握解决Spring Boot应用上传文件时报错“spring.servlet.multipart.location”的方法的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注天达云行业资讯频道,感谢各位的阅读!