Java 多个文件生成zip包、下载zip包的实现代码

 更新时间:2024年01月28日 16:24:26   作者:胡萝卜★  
这篇文章主要介绍了Java 多个文件生成zip包、下载zip包,包括文件上传,文件下载,多个文件打成zip包的操作代码,本文给大家介绍的非常详细,需要的朋友可以参考下

Java 多个文件生成zip包、下载zip包

一、文件上传

代码实现

 	/**
     * 点击按钮 文件上传
     */
    @PostMapping("/uploadFile")
    public String uploadFile(@RequestParam("file") MultipartFile file){
        String upload = fileService.upload(file);
        System.out.println("upload:"+upload);
        return "上传成功对应路径:"+upload;
    }
public  String  upload(MultipartFile file){
    	//上传路径
        String path = "D:\\var\\file\\uploadFile"+"\\"+file.getOriginalFilename();
        String fileSavePath = null;
        try {
            boolean upload = this.saveFileUpload(path, this.multipartFileToFile(file));
            if (upload) {
                fileSavePath = path;
            }
        } catch (Exception e) {
            log.error("文件上传失败,", e);
        }
        return fileSavePath;
    }
    /**
     *
     * @param savePath 保存路径
     * @param file
     * @return
     */
    public  boolean saveFileUpload(String savePath, File file) {
        try {
            if (StringUtils.isEmpty(savePath)) {
                log.info("savePath is null");
                return false;
            }
            log.info("save file path : " + savePath);
            java.nio.file.Files.copy(file.toPath(), new File(savePath).toPath());
            return true;
        } catch (IOException e) {
            log.error("saveFileUpload error", e);
        }
        return false;
    }
    /**
     * MultipartFile 转 File
     */
    public File multipartFileToFile(MultipartFile file) {
        File toFile = null;
        try{
            if (file == null || StringUtils.isEmpty(file.getOriginalFilename()) || file.getSize() <= 0) {
                return null;
            } else {
                InputStream ins;
                ins = file.getInputStream();
                toFile = new File(file.getOriginalFilename());
                inputStreamToFile(ins, toFile);
                ins.close();
            }
        }catch (Exception e){
            log.error("multipartFileToFile err", e);
        }
        return toFile;
    }
    /**
     *  获取文件流
     */
    private  void inputStreamToFile(InputStream ins, File file) {
        try {
            OutputStream os = new FileOutputStream(file);
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            ins.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

结果展示

在这里插入图片描述

二、多个文件打成zip包

代码实现

 @PostMapping("/yaZipFile")
    public String yaZipFile() {
        fileService.yaZipFile();
        return "压缩成功";
    }

路径 可以从前端传过来

public void yaZipFile() {
        try {
            //进行压缩
            boolean b = FileDownloadUtils.generateFile("D:\\var\\file\\uploadFile", "zip", "D:\\var\\file", "uploadFiles");
            if(b){
                log.info("压缩成功....");
                File sourceFile = new File("D:\\var\\file\\uploadFile");
                boolean flag = FileDownloadUtils.deleteDir(sourceFile);
                if(flag){
                    log.info("删除成功.....");
                }
            }
        }catch (Exception e){
            log.error("发生异常error:{}",e);
        }
    }
 /**
     * @param path    要压缩的文件路径
     * @param format  生成的格式(zip、rar)
     * @param zipPath zip的路径
     * @param zipName zip文件名
     * @Description 将多个文件进行压缩到指定位置
     */
    public static boolean generateFile(String path, String format, String zipPath, String zipName) throws Exception {
        File file = new File(path);
        // 压缩文件的路径不存在
        if (!file.exists()) {
            throw new Exception("路径 " + path + " 不存在文件,无法进行压缩...");
        }
        // 用于存放压缩文件的文件夹
        String generateFile = zipPath + File.separator;
        File compress = new File(generateFile);
        // 如果文件夹不存在,进行创建
        if (!compress.exists()) {
            compress.mkdirs();
        }
        // 目的压缩文件
        String generateFileName = compress.getAbsolutePath() + File.separator + zipName + "." + format;
        // 输出流
        FileOutputStream outputStream = new FileOutputStream(generateFileName);
        // 压缩输出流
        ZipOutputStream zipOutputStream = new ZipOutputStream(new BufferedOutputStream(outputStream));
        //压缩
        generateFile(zipOutputStream, file, "");
        System.out.println("源文件位置:" + file.getAbsolutePath() + ",目的压缩文件生成位置:" + generateFileName);
        // 关闭 输出流
        zipOutputStream.close();
        return true;
    }
    /**
     * @param out  输出流
     * @param file 目标文件
     * @param dir  文件夹
     * @throws Exception
     */
    private static void generateFile(ZipOutputStream out, File file, String dir) throws Exception {
        // 当前的是文件夹,则进行一步处理
        if (file.isDirectory()) {
            //得到文件列表信息
            File[] files = file.listFiles();
            //将文件夹添加到下一级打包目录
            out.putNextEntry(new ZipEntry(dir + "/"));
            dir = dir.length() == 0 ? "" : dir + "/";
            //循环将文件夹中的文件打包
            for (int i = 0; i < files.length; i++) {
                generateFile(out, files[i], dir + files[i].getName());
            }
        } else { // 当前是文件
            // 输入流
            FileInputStream inputStream = new FileInputStream(file);
            // 标记要打包的条目
            out.putNextEntry(new ZipEntry(dir));
            // 进行写操作
            int len = 0;
            byte[] bytes = new byte[1024];
            while ((len = inputStream.read(bytes)) > 0) {
                out.write(bytes, 0, len);
            }
            // 关闭输入流
            inputStream.close();
        }
    }

结果展示:

压缩包生成,把之前的目录删除

三、文件下载

代码实现

 @PostMapping("/downZipFile")
    public String downZipFile(HttpServletResponse response){
        fileService.downZipFile(response);
        return "下载成功";
    }

路径、文件名 也可以从前端传过来

public void downZipFile(HttpServletResponse response){
        String title = "uploadFiles.zip";
        //压缩文件路径 D:\var\file
        File filePath = new File("D:\\var\\file" + File.separator + title);
        String filename = System.currentTimeMillis()+"_"+title;
        //设置文件路径
        if (filePath.exists()) {
            FileInputStream fis = null;
            BufferedInputStream bis = null;
            try {
                //设置下载文件类型
                response.setContentType("application/octet-stream");
                response.setHeader("Content-disposition", "attachment; filename=" + new String(filename.getBytes("utf-8"), "ISO8859-1"));
                byte[] buffer = new byte[4096];
                fis = new FileInputStream(filePath);
                bis = new BufferedInputStream(fis);
                OutputStream os = response.getOutputStream();
                int i = bis.read(buffer);
                while (i != -1) {
                    os.write(buffer, 0, i);
                    i = bis.read(buffer);
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (bis != null) {
                    try {
                        bis.close();
                        // 删除临时文件
                        filePath.delete();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (fis != null) {
                    try {
                        fis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

结果展示

java 批量下载将多个文件(minio中存储)压缩成一个zip包

到此这篇关于Java 多个文件生成zip包、下载zip包的文章就介绍到这了,更多相关Java 多个文件生成zip包内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • java中如何判断JSONObject是否存在某个Key

    java中如何判断JSONObject是否存在某个Key

    这篇文章主要介绍了java中如何判断JSONObject是否存在某个Key,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-07-07
  • Spring Boot 文件上传原理解析

    Spring Boot 文件上传原理解析

    Spring Boot 文件上传原理其实就是Spring MVC,因为这部分工作是Spring MVC做的而不是Spring Boot,那么,SpringMVC又是怎么处理文件上传这个过程的呢?下面通过本文给大家详细介绍下,一起看看吧
    2018-03-03
  • 解决Spring使用@MapperScan问题

    解决Spring使用@MapperScan问题

    这篇文章主要介绍了解决Spring使用@MapperScan问题,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2021-09-09
  • SpringBoot集成Caffeine缓存的实现步骤

    SpringBoot集成Caffeine缓存的实现步骤

    Caffeine cache是一个针对Java的高性能缓存库。在本文中,我们将介绍它与Spring Boot如何一起使用。
    2021-05-05
  • 浅谈Java设计模式之原型模式知识总结

    浅谈Java设计模式之原型模式知识总结

    Java原型模式主要用于创建重复的对象,同时又能保证性能,这篇文章就带大家仔细了解一下原型模式的知识,对正在学习java的小伙伴们很有帮助,需要的朋友可以参考下
    2021-05-05
  • JAVA调用JavaScript方法举例详解

    JAVA调用JavaScript方法举例详解

    之前在一次机缘巧合的情况下,需要时用JAVA执行js方法,查阅了一些文档,找到了相关解决方法,这里和大家分享一下,下面这篇文章主要给大家介绍了关于JAVA调用JavaScript方法的相关资料,需要的朋友可以参考下
    2023-10-10
  • 开源项目ERM模型转jpa实体maven插件使用

    开源项目ERM模型转jpa实体maven插件使用

    这篇文章主要为大家介绍了开源项目ERM模型转jpa实体maven插件的使用说明,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步
    2022-03-03
  • 使用java基础类实现zip压缩和zip解压工具类分享

    使用java基础类实现zip压缩和zip解压工具类分享

    使用java基础类写的一个简单的zip压缩解压工具类,实现了指定目录压缩到和该目录同名的zip文件和将zip文件解压到指定的目录的功能
    2014-03-03
  • 一篇文章带你Java Spring开发入门

    一篇文章带你Java Spring开发入门

    这篇文章主要为大家详细介绍了Java Spring开发入门学习教程,具有一定的参考价值,感兴趣的小伙伴们可以参考一下,希望能够给你带来帮助
    2021-09-09
  • SpringBoot日期格式转换之配置全局日期格式转换器的实例详解

    SpringBoot日期格式转换之配置全局日期格式转换器的实例详解

    这篇文章主要介绍了SpringBoot日期格式转换之配置全局日期格式转换器的实例详解,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2020-12-12

最新评论