温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

解决Spring Boot应用上传文件时报错“spring.servlet.multipart.location”的方法

发布时间:2020-11-11 17:34:19 来源:亿速云 阅读:5605 作者:Leah 栏目:编程语言

解决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”的方法的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注亿速云行业资讯频道,感谢各位的阅读!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI