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()关闭是针对往压缩文件写入实体,同时要排查流的关闭顺序是否正确,先打开的流,最后关闭。

  • 3
    点赞
  • 35
    收藏
    觉得还不错? 一键收藏
  • 21
    评论
你可以使用Java提供的ZipOutputStream类来创建一个zip压缩文件,然后将下载文件添加到该压缩文件中。下面是一段示例代码: ```java import java.io.*; import java.net.URL; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; public class DownloadAndZip { public static void main(String[] args) throws Exception { // 下载文件 URL url = new URL("http://example.com/file.txt"); InputStream in = url.openStream(); FileOutputStream fos = new FileOutputStream("file.txt"); byte[] buffer = new byte[1024]; int length; while ((length = in.read(buffer)) > 0) { fos.write(buffer, 0, length); } in.close(); fos.close(); // 创建zip文件并添加下载文件到其中 FileOutputStream fosZip = new FileOutputStream("file.zip"); ZipOutputStream zipOut = new ZipOutputStream(fosZip); File fileToZip = new File("file.txt"); FileInputStream fis = new FileInputStream(fileToZip); ZipEntry zipEntry = new ZipEntry(fileToZip.getName()); zipOut.putNextEntry(zipEntry); byte[] bytes = new byte[1024]; int lengthZip; while ((lengthZip = fis.read(bytes)) >= 0) { zipOut.write(bytes, 0, lengthZip); } fis.close(); zipOut.closeEntry(); zipOut.close(); fosZip.close(); } } ``` 在上面的示例中,我们首先从指定的URL下载文件并保存到本地文件“file.txt”中。接下来,我们创建一个ZipOutputStream对象,并将下载文件添加到其中。最后,我们将ZipOutputStream写入到一个新的文件“file.zip”中,并关闭所有的输入和输出流。
评论 21
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值