美文网首页
上传文件 java.io.IOException: The te

上传文件 java.io.IOException: The te

作者: 墨色尘埃 | 来源:发表于2019-05-17 14:30 被阅读0次

使用springboot框架进行文件上传时报错,错误如下:

Could not parse multipart servlet request; nested exception is java.io.IOException: The temporary upload location [/tmp/tomcat.7333297176951596407.9000/work/Tomcat/localhost/ROOT] is not valid

错误原因:
/tmp/tomcat.7333297176951596407.9000/work/Tomcat/localhost/ROOT 文件夹不存在

错误分析:
在springboot项目启动后,系统会在‘/tmp’目录下自动的创建几个目录(我的项目是以下的文件夹):
1,hsperfdata_root,
2,tomcat.************.10002,(结尾是项目的端口)
3,tomcat-docbase.*********.8080。
Multipart(form-data)的方式处理请求时,默认就是在第二个目录下创建临时文件的。

这篇文章对自动清理文件有很好的说明 CentOS7的/tmp目录自动清理规则
如图:

image.png

查阅资料后,发现是centos对'/tmp'下文件自动清理的原因。
tmp文件夹 有个特性 ,就是在10天内没有进行操作,该文件夹内的文件夹和文件等就会自动被清除,导致一些文件丢失。

解决方法:

方法一:直接从新启动项目即可解决(这个只能治标不治本)
方法二:指定上传文件临时的路径(从根本解决),如下:
① 在启动类里面添加MultipartConfigElement 配置类

    @Bean
    MultipartConfigElement multipartConfigElement() {
        MultipartConfigFactory factory = new MultipartConfigFactory();
        String location = System.getProperty("user.dir") + "/data/tmp";
        File tmpFile = new File(location);
        if (!tmpFile.exists()) {
            tmpFile.mkdirs();
        }
        factory.setLocation(location);
        return factory.createMultipartConfig();
    }

② 或者新建一个配置类MultipartConfig

@Configuration
public class MultipartConfig {

    /**
     * 文件上传临时路径
     */
    @Bean
    MultipartConfigElement multipartConfigElement() {
        MultipartConfigFactory factory = new MultipartConfigFactory();
        String location = System.getProperty("user.dir") + "/data/tmp";
        File tmpFile = new File(location);
        if (!tmpFile.exists()) {
            tmpFile.mkdirs();
        }
        factory.setLocation(location);
        return factory.createMultipartConfig();
    }
}

方法三:
在propertites文件中配置: spring.http.multipart.location= 你的缓存文件路径
或者是pom.yml文件中配置:

spring:
  http:
    multipart:
      max-file-size: 50Mb
      max-request-size: 80Mb
      location: F:/Files/jscmp/temp
#      location: file:/F:/Files/jscmp/temp  这个是错误的

相关文章

网友评论

      本文标题:上传文件 java.io.IOException: The te

      本文链接:https://www.haomeiwen.com/subject/znspaqtx.html