SpringBoot上传ZIP文件并保存文件信息


添加Jar包



            net.lingala.zip4j
            zip4j
            1.3.1
        


        
            commons-io
            commons-io
            2.6
        

代码实现

public void doZipFile(MultipartFile file) {
        if(file != null) {
            // 上传文件的路径
            long time = TimeTools.get0TimeZone();
            String uploadFolder = GlobalVar.UPLOAD_PREFIX + UploadTypeEnum.getDir(2) + "/" + time + "/";
            String fileName = file.getOriginalFilename();
            String extension = fileName.substring(fileName.lastIndexOf("."));
            fileName = UUID.randomUUID() + extension;
            File dest = new File(uploadFolder + fileName);
            // 检测文件目录是否存在 不存在则创建
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdirs();
            }
            try {
                file.transferTo(dest);
            } catch (IOException e) {
                e.printStackTrace();
                throw new CheckException("文件上传失败");
            }
            ZipFile zipFile = null;
            try {
                zipFile = new ZipFile(dest);
                zipFile.setFileNameCharset("utf-8");
                zipFile.extractAll(uploadFolder);
                Collection files = FileUtils.listFiles(dest.getParentFile(),
                        GlobalVar.IMG_SUFFIX.toArray(new String[0]), true);
                files.stream().forEach(e -> {
                    if(!e.getName().startsWith(".")) {
                        VirtualImg virtualImg = new VirtualImg();
                        virtualImg.setHeadImg("/uploads/" + UploadTypeEnum.getDir(2) + "/" + time + "/" + e.getName());
                        this.save(virtualImg);
                    }
                });
            } catch (ZipException e) {
                e.printStackTrace();
            }
        }
    }