解决办法

(1)通过Spring Boot的配置参数“spring.servlet.multipart.location”明确指定上传文件的临时目录,确保该路径已经存在,而且该目录不会被操作系统清除。

spring.servlet.multipart.location=/data/tmp

将上传文件的临时目录指定到路径“/data/tmp”下。

实际上,在Spring Boot中关于上传文件的所有配置参数如下所示:

 

//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package javax.servlet;

import javax.servlet.annotation.MultipartConfig;

public class MultipartConfigElement {
    private String location;
    private long maxFileSize;
    private long maxRequestSize;
    private int fileSizeThreshold;

    public MultipartConfigElement(String location) {
        if (location == null) {
            this.location = "";
        } else {
            this.location = location;
        }

        this.maxFileSize = -1L;
        this.maxRequestSize = -1L;
        this.fileSizeThreshold = 0;
    }

    public MultipartConfigElement(String location, long maxFileSize, long maxRequestSize, int fileSizeThreshold) {
        if (location == null) {
            this.location = "";
        } else {
            this.location = location;
        }

        this.maxFileSize = maxFileSize;
        this.maxRequestSize = maxRequestSize;
        this.fileSizeThreshold = fileSizeThreshold;
    }

    public MultipartConfigElement(MultipartConfig annotation) {
        this.location = annotation.location();
        this.fileSizeThreshold = annotation.fileSizeThreshold();
        this.maxFileSize = annotation.maxFileSize();
        this.maxRequestSize = annotation.maxRequestSize();
    }

    public String getLocation() {
        return this.location;
    }

    public long getMaxFileSize() {
        return this.maxFileSize;
    }

    public long getMaxRequestSize() {
        return this.maxRequestSize;
    }

    public int getFileSizeThreshold() {
        return this.fileSizeThreshold;
    }
}

2)在Spring容器中明确注册MultipartConfigElement对象,通过MultipartConfigFactory指定一个路径。
在上述源码追踪中就发现,Tomcat会使用MultipartConfigElement对象的location属性作为上传文件的临时目录。

    /**
     * 配置上传文件临时目录
     *
     * @return
     */
    @Bean
    public MultipartConfigElement multipartConfigElement() {
        MultipartConfigFactory factory = new MultipartConfigFactory();
        String path = System.getProperty("user.dir");
        File tmpFile = new File(path);    // 如果临时目录不存在则创建
        if (!tmpFile.exists()) {
            tmpFile.mkdirs();
        }
        // 明确指定上传文件的临时目录
        factory.setLocation(path);
        return factory.createMultipartConfig();
    }

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐