Java实现文件批量下载,打包成zip压缩包

   最近在做一个管理系统的项目,需要实现一个功能,就是批量下载文件,并打包成zip压缩包。
   前端通过POST请求传来要下载的文件列表,Java代码实现如下:

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

/** * @author XXX * @version 1.0 * @date 2021年10月15日 */
public class Test { 

    /** * 日志输出对象 */
    private static Logger logger = LoggerFactory.getLogger(Test.class);

    /** * 文件路径 举例:D:\data\test\file\ */
    @Value("${path}")
    private String path;

    /** * 文件下载 * * @param param * @return */
    @RequestMapping(value = "/test/downloadfile.action", method = RequestMethod.POST)
    @ResponseBody
    public void downloadFile(@RequestBody String param,HttpServletRequest request, HttpServletResponse response) { 

        OutputStream os = null;
        ZipOutputStream zos = null;
        BufferedInputStream bis = null;
        FileInputStream in = null;   

        try { 
            ObjectMapper objectMapper = new ObjectMapper();
            JsonNode root = objectMapper.readTree(param);

            if (root != null) { 
                JsonNode dataNode = root.findValue("fileNameList");
                List<String> fileNameList = objectMapper.readValue(dataNode.toString(), new TypeReference<List<String>>(){ });

                // 通过response对象获取OutputStream流
                os = response.getOutputStream();
                // 获取zip的输出流
                zos = new ZipOutputStream(os);

                // 遍历文件名列表添加进压缩包
                for (int i = 0; i < fileNameList.size(); i++) { 
                    String fileName = fileNameList.get(i);
                    String filePath = path + fileName;

                    File file = new File(filePath);
                    if (file.exists()) { 
                        // 读取文件流
                        in = new FileInputStream(file);

                        // 创建ZIP实体,并添加进压缩包
                        ZipEntry zipEntry = new ZipEntry(fileName);
                        zos.putNextEntry(zipEntry);

                        // 设置压缩后的文件名
                        String zipFileName = "dataFile.zip";
                        // 设置Content-Disposition响应头,控制浏览器弹出保存框,若没有此句浏览器会直接打开并显示文件
                        // 中文名要进行URLEncoder.encode编码,否则客户端能下载但名字会乱码
                        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(zipFileName, "UTF-8"));

                        // 输入缓冲流
                        bis = new BufferedInputStream(in, 1024 * 10);
                        // 创建读写缓冲区
                        byte[] buf = new byte[1024 * 10];
                        int len = 0;
                        while ((len = bis.read(buf, 0, 1024 * 10)) > 0) { 
                            // 使用OutputStream将缓冲区的数据输出到客户端浏览器
                            zos.write(buf, 0, len);
                        }
                        bis.close();
                        in.close();
                        zos.closeEntry();
                    }
                }
            }
        } catch (Exception e) { 
            logger.error("下载文件异常:" + e.toString());
        } finally { 
            try { 
                if(null != bis){ 
                    bis.close();
                } 
                if(null != in){ 
                    in.close();
                }
                if(null != zos){ 
                    zos.close();
                }
                    if(null != os){ 
                os.close();
                }
            } catch (Exception e2) { 
                logger.error(e2.toString());
            }
        }
    }
}

   有些同学会遇到下载下来文件解压报错的情况,一定要检查流是否关闭,流关闭一定要用close(),closeEntry()关闭是针对往压缩文件写入实体,同时要排查流的关闭顺序是否正确,先打开的流,最后关闭。

    原文作者:冬日蓝天lyyeagle
    原文地址: https://blog.csdn.net/LYY1448019681/article/details/120788021
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞