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

}

总结

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

相关文章

  • Zookeeper ZkClient使用介绍

    Zookeeper ZkClient使用介绍

    ZkClient是Github上⼀个开源的zookeeper客户端,在Zookeeper原生API接口之上进行了包装,是⼀个更易用的Zookeeper客户端,同时,zkClient在内部还实现了诸如Session超时重连、Watcher反复注册等功能
    2022-09-09
  • 详解Java 本地接口 JNI 使用方法

    详解Java 本地接口 JNI 使用方法

    这篇文章主要介绍了详解Java 本地接口 JNI 使用方法的相关资料,希望通过本文大家能彻底使用JNI编程,需要的朋友可以参考下
    2017-09-09
  • 解决Mybatis mappe同时传递 List 和其他参数报错的问题

    解决Mybatis mappe同时传递 List 和其他参数报错的问题

    在使用MyBatis时,如果需要传递多个参数到SQL中,可以遇到参数绑定问题,解决方法包括使用@Param注解和修改mapper.xml配置,感兴趣的朋友跟随小编一起看看吧
    2024-09-09
  • Java服务端性能优化之JVM垃圾回收策略详解

    Java服务端性能优化之JVM垃圾回收策略详解

    JVM垃圾回收策略涵盖了基本原理、常见策略(如SerialGC、ParallelGC、CMS、G1GC)以及优化建议,选择合适的策略和调整参数,如堆大小和GC日志,可以提高应用性能和响应速度,持续监控和分析是关键步骤
    2025-03-03
  • 基于Java子线程中的异常处理方法(通用)

    基于Java子线程中的异常处理方法(通用)

    下面小编就为大家带来一篇基于Java子线程中的异常处理方法(通用)。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-09-09
  • springboot整合RabbitMQ中死信队列的实现

    springboot整合RabbitMQ中死信队列的实现

    死信是无法被消费的消息,产生原因包括消息TTL过期、队列最大长度达到以及消息被拒绝且不重新排队,RabbitMQ的死信队列机制能够有效防止消息数据丢失,适用于订单业务等场景,本文就来介绍一下
    2024-10-10
  • java实现省市区三级联动

    java实现省市区三级联动

    这篇文章主要为大家详细介绍了java实现省市区三级联动,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2022-06-06
  • 解析Java的Spring框架的BeanPostProcessor发布处理器

    解析Java的Spring框架的BeanPostProcessor发布处理器

    这篇文章主要介绍了Java的Spring框架的BeanPostProcessor发布处理器,Spring是Java的SSH三大web开发框架之一,需要的朋友可以参考下
    2015-12-12
  • java实现收藏名言语句台词的app

    java实现收藏名言语句台词的app

    本文给大家分享的是使用java制作的记录名人名言台词等等让你难忘的语句的APP的代码,非常的实用,有需要的小伙伴可以参考下。
    2015-04-04
  • 详解SpringBoot中使用JPA作为数据持久化框架

    详解SpringBoot中使用JPA作为数据持久化框架

    这篇文章主要介绍了SpringBoot中使用JPA作为数据持久化框架的相关知识,本文通过示例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2023-03-03

最新评论