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

 更新时间:2025年04月21日 08:57:10   作者:叶梓啊  
这篇文章主要介绍了Java springboot压缩文件上传,解压,删除压缩包方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教

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);
    }

}

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

相关文章

  • JavaWeb项目中JSP访问的问题解决

    JavaWeb项目中JSP访问的问题解决

    JSP文件一般有两个存放位置,本文主要介绍了JavaWeb项目中JSP访问的问题解决,具有一定的参考价值,感兴趣的可以了解一下
    2024-01-01
  • Java 二叉树遍历特别篇之Morris遍历

    Java 二叉树遍历特别篇之Morris遍历

    二叉树的遍历(traversing binary tree)是指从根结点出发,按照某种次序依次访问二叉树中所有的结点,使得每个结点被访问依次且仅被访问一次。四种遍历方式分别为:先序遍历、中序遍历、后序遍历、层序遍历
    2021-11-11
  • 解决SpringSecurity 一直登录失败的问题

    解决SpringSecurity 一直登录失败的问题

    这篇文章主要介绍了解决SpringSecurity 一直登录失败的问题,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2021-06-06
  • Java多线程模拟银行系统存钱问题详解

    Java多线程模拟银行系统存钱问题详解

    本文将利用Java多线程模拟一个简单的银行系统,使用两个不同的线程向同一个账户存钱。文中的示例代码讲解详细,感兴趣的可以了解一下
    2022-09-09
  • Spring高级注解@PropertySource详细解读

    Spring高级注解@PropertySource详细解读

    这篇文章主要介绍了Spring高级注解@PropertySource详细解读,@PropertySource注解用于指定资源文件读取的位置,它不仅能读取properties文件,也能读取xml文件,并且通过YAML解析器,配合自定义PropertySourceFactory实现解析yaml文件,需要的朋友可以参考下
    2023-11-11
  • SpringMVC 限流的示例代码

    SpringMVC 限流的示例代码

    这篇文章主要介绍了SpringMVC 限流的示例代码,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-12-12
  • java实现学生宿舍系统

    java实现学生宿舍系统

    这篇文章主要为大家详细介绍了java实现学生宿舍系统,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2022-03-03
  • Java多线程Runable售票系统实现过程解析

    Java多线程Runable售票系统实现过程解析

    这篇文章主要介绍了Java多线程Runable售票系统实现过程解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-06-06
  • IntelliJ IDEA 2018 最新激活码(截止到2018年1月30日)

    IntelliJ IDEA 2018 最新激活码(截止到2018年1月30日)

    这篇文章主要介绍了IntelliJ IDEA 2018 最新激活码(截止到2018年1月30日)的相关资料,需要的朋友可以参考下
    2018-01-01
  • 将java项目打包成exe可执行文件的完整步骤

    将java项目打包成exe可执行文件的完整步骤

    最近项目要求,需要将java项目生成exe文件,下面这篇文章主要给大家介绍了关于如何将java项目打包成exe可执行文件的相关资料,文章通过图文介绍的非常详细,需要的朋友可以参考下
    2022-06-06

最新评论