webkitdirectory实现文件夹上传


webkitdirectory

HTMLInputElement.webkitdirectory是属于元素的一个HTML属性webkitdirectory,它可以选择一个文件夹,文件夹里的文件夹和文件都可以上传上去。,但是这个属性不是标准化的,不适用于IE浏览器和火狐浏览器。
详情可以参考webkitdirectory

上传文件夹demo

1. 配置application.properties(防止报文件大小错误)

spring.servlet.multipart.max-file-size=1000MB
spring.servlet.multipart.max-request-size=1000MB

2. 前端页面




    
    Files Uploader
    


    

页面操作:

3. 工具类

public class FileUtil {

    /**
     * 在basePath下保存上传的文件夹
     *
     * @param basePath
     * @param files
     */
    public static void saveMultiFile(String basePath, MultipartFile[] files) {
        if (files == null || files.length == 0) {
            System.out.println("no files uploaded");
            return;
        } else if (files[0].getOriginalFilename() == null || files[0].getOriginalFilename().equals("")) {
            System.out.println("Empty package: no files to be uploaded");
            return;
        }
        if (basePath.endsWith("/")) {
            basePath = basePath.substring(0, basePath.length() - 1);
        }
        for (MultipartFile file : files) {
            String relativePath = file.getOriginalFilename();
            String filePath = basePath + "/" + relativePath;
            System.out.println("uploading " + relativePath + " to " + filePath + "......");
            makeDir(filePath);
            File dest = new File(filePath);
            try {
                file.transferTo(dest);
                System.out.println("successful upload");
            } catch (IllegalStateException | IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 确保目录存在,不存在则创建
     *
     * @param filePath
     */
    private static void makeDir(String filePath) {
        if (filePath.lastIndexOf('/') > 0) {
            String dirPath = filePath.substring(0, filePath.lastIndexOf('/'));
            File dir = new File(dirPath);
            if (!dir.exists()) {
                dir.mkdirs();
            }
        }
    }
}

4.controller

@RestController
public class UploadFileController {

    @PostMapping(value = "/uploadFolder")
    public String uploadFolder(@RequestParam MultipartFile[] folder) {
        FileUtil.saveMultiFile("G:\\temp", folder);
        return "success";
    }
}