欢迎访问悦橙教程(wld5.com),关注java教程。悦橙教程  java问答|  每日更新
页面导航 : > > 文章正文

Javaspringboot压缩文件上传,解压,删除压缩包方式,

来源: javaer 分享于  点击 15994 次 点评:179

Javaspringboot压缩文件上传,解压,删除压缩包方式,


目录
  • Java springboot压缩文件上传,解压,删除压缩包
    • 1. 配置文件
    • 2. 工具类
    • 3. 使用
  • 总结

    Java springboot压缩文件上传,解压,删除压缩包

    1. 配置文件

    在application.yml里

    file-server:
      path: \material-main\
      # 自己随便命名。注意,不管windows还是linux,路径不需要带盘符,用代码去识别即可

    2. 工具类

    如果需要删除压缩包,把下边的注释解开

    import lombok.extern.slf4j.Slf4j;
    
    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.util.Enumeration;
    import java.util.zip.ZipEntry;
    import java.util.zip.ZipFile;
    
    @Slf4j
    public class UnzipUtils {
    
        /**
         * 传文件绝对路径
         */
        public static void zipUncompress(String inputFile) {
            log.info("UnzipUtils开始解压");
            File oriFile = new File(inputFile);
            // 判断源文件是否存在
            String destDirPath = inputFile.replace(".zip", "");
            FileOutputStream fos = null;
            InputStream is = null;
            ZipFile zipFile = null;
            try {
                //创建压缩文件对象
                zipFile = new ZipFile(oriFile);
                //开始解压
                Enumeration<?> entries = zipFile.entries();
                while (entries.hasMoreElements()) {
                    ZipEntry entry = (ZipEntry) entries.nextElement();
                    // 如果是文件夹,就创建个文件夹
                    if (entry.isDirectory()) {
                        oriFile.mkdirs();
                    } else {
                        // 如果是文件,就先创建一个文件,然后用io流把内容copy过去
                        File targetFile = new File(destDirPath + "/" + entry.getName());
                        // 保证这个文件的父文件夹必须要存在
                        if (!targetFile.getParentFile().exists()) {
                            targetFile.getParentFile().mkdirs();
                        }
                        targetFile.createNewFile();
                        // 将压缩文件内容写入到这个文件中
                        is = zipFile.getInputStream(entry);
                        fos = new FileOutputStream(targetFile);
                        int len;
                        byte[] buf = new byte[1024];
                        while ((len = is.read(buf)) != -1) {
                            fos.write(buf, 0, len);
                        }
                    }
                }
            } catch (Exception e) {
                log.error("文件解压过程中异常,{}", e);
            } finally {
                // 关流顺序,先打开的后关闭
                try {
                    if (fos != null) {
                        fos.close();
                    }
                    if (is != null) {
                        is.close();
                    }
                    if (zipFile != null) {
                        zipFile.close();
                    }
                } catch (IOException e) {
                    log.error("文件流关闭异常,{}", e);
                }
            }
            //解压后删除文件
    //        if (oriFile.exists()) {
    //            System.gc();
    //            oriFile.delete();
    //            if (oriFile.exists()) {
    //                System.gc();
    //                oriFile.delete();
    //                if (oriFile.exists()) {
    //                    log.error("文件未被删除");
    //                }
    //            }
    //        }
            log.info("UnzipUtils解压完成");
        }
    }
    

    3. 使用

    controller层。注意,我用的swagger3,也就是springdoc。

    用swagger2(springfox)的,写法没这么麻烦

    package com.mods.browser.controller;
    
    import com.mods.browser.service.IFilesService;
    import com.mods.common.result.Result;
    import io.swagger.v3.oas.annotations.Operation;
    import io.swagger.v3.oas.annotations.tags.Tag;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.http.MediaType;
    import org.springframework.web.bind.annotation.*;
    import org.springframework.web.multipart.MultipartFile;
    
    @RestController
    @RequestMapping("/files")
    @Tag(name = "FilesController", description = "文件管理")
    public class FilesController {
    
        @Autowired
        private IFilesService filesService;
    
        //swagger3写法
        @PostMapping(value = "/file/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
        @Operation(summary = "上传zip文件至服务器中")
        public Result uploadFile(@RequestPart("file") MultipartFile file) {
            return filesService.uploadFile(file);
        }
        
    //	  swagger2写法
    //    @ApiOperation("上传zip文件")
    //    @PostMapping("/file/upload")
    //    public Result uploadFile(MultipartFile file) {
    //        return filesService.uploadFile(file);
    //    }
    
    
    }
    

    service具体业务

    package com.mods.browser.service.impl;
    
    import com.mods.browser.service.IFilesService;
    import com.mods.common.exception.CommonException;
    import com.mods.common.result.Result;
    import com.mods.common.result.ResultCode;
    import com.mods.common.utils.FileUtils;
    import com.mods.common.utils.MyDateUtils;
    import com.mods.common.utils.UnzipUtils;
    import lombok.extern.slf4j.Slf4j;
    import org.apache.commons.lang3.StringUtils;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.stereotype.Service;
    import org.springframework.web.multipart.MultipartFile;
    
    import java.io.File;
    import java.io.IOException;
    import java.io.InputStream;
    import java.nio.file.Files;
    import java.nio.file.Path;
    import java.nio.file.Paths;
    import java.util.*;
    
    @Service
    @Slf4j
    public class FilesServiceImpl implements IFilesService {
    
        @Value("${file-server.path}")
        private String uploadPath;
    
        private String getUploadPath() {//智能识别补全路径
            Properties props = System.getProperties();
            String property = props.getProperty("os.name");
            String userHomePath = props.getProperty("user.home");
            String filePath = "";//文件存放地址
            if (property.contains("Windows")) {
                String[] arr = userHomePath.split(":");
                String pan = arr[0] + ":";//windows会取第一个盘盘符
                filePath = pan + uploadPath;
            } else if (property.contains("Linux")) {
                filePath = uploadPath;
            }
            return filePath;
        }
    
        @Override
        public Result uploadFile(MultipartFile file) {
            String originalFilename = file.getOriginalFilename();//原始名称
            if (StringUtils.isBlank(originalFilename) || !originalFilename.endsWith(".zip")) {
                return new Result(ResultCode.FILE_WRONG);
            }
            String newName = UUID.randomUUID().toString().replace("-", "");//uuid作为文件夹新名称,不重复
            String zipName = newName + ".zip";//uuid作为压缩文件新名称,不重复
            //创建文件夹,今天的日期
            String date = MyDateUtils.parseDate2String(new Date());
            //文件存放位置,加一层日期
            String path = getUploadPath() + date;
            //返回结果
            Map<String, Object> pathMap = new HashMap<>();
            InputStream inputStream = null;//文件流
            try {
                inputStream = file.getInputStream();
                //检测创建文件夹
                Path directory = Paths.get(path);
                if (!Files.exists(directory)) {
                    Files.createDirectories(directory);
                }
                Long size = Files.copy(inputStream, directory.resolve(zipName));//上传文件,返回值是文件大小
                pathMap.put("zip_size", size);
            } catch (Exception e) {
                pathMap.put("zip_size", 0);
                return new Result(e);
            } finally {
                try {
                    if (inputStream != null) {
                        inputStream.close();
                    }
                } catch (IOException e) {
                    throw new CommonException(e.getMessage());
                }
            }
            String zipPath = path + File.separator + zipName;
            UnzipUtils.zipUncompress(zipPath);
            pathMap.put("main_path", zipPath);
            pathMap.put("folder_path", path + File.separator + newName);
            pathMap.put("zip_size_cent", "kb");
            return new Result(pathMap);
        }
    
        @Override
        public Result fileDel(String downloadPath) {
            String absolutePath = FileUtils.getPathAndName(this.getUploadPath(), downloadPath);
            boolean b = FileUtils.deleteFile(absolutePath);
            return new Result(b);
        }
    
    }
    

    总结

    以上为个人经验,希望能给大家一个参考,也希望大家多多支持3672js教程。

    您可能感兴趣的文章:
    • java打包文件成zip、压缩文件及file.mkdir和mkdirs的区别详解
    • Java处理压缩文件的步骤详解
    • Java如何生成压缩文件工具类
    • java文件删除不了的坑,特别是压缩文件问题
    • Java中解压缩文件的方法详解(通用)
    相关栏目:

    用户点评