Java打包下载zip文件


import org.apache.commons.io.IOUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;
import java.util.zip.CRC32;
import java.util.zip.CheckedOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class ZipDownloadUtil {

    /**
     *
     * @param response
     * @param zipFilename zip的文件名
     * @param contentList 每个文件的字节流
     * @param filenameList 每个文件的文件名(如果想包含文件夹可命名为   文件夹名称/文件名.png 例:  高一(1)班/小陈.png)
     * @throws IOException
     */
    public static void downloadZip(HttpServletResponse response,
                                   String zipFilename,
                                   List contentList,
                                   List filenameList) throws IOException {
        response.reset();
        response.setContentType("application/x-msdownload;");
        response.setHeader("Content-Disposition", "attachment;filename="
                + new String((zipFilename).getBytes(), "iso-8859-1"));

        ByteArrayOutputStream output = new ByteArrayOutputStream();
        CheckedOutputStream cos = new CheckedOutputStream(output, new CRC32());
        ZipOutputStream zos = new ZipOutputStream(cos);


        for (int i = 0; i < contentList.size(); i++) {
            byte[] content = contentList.get(i);
            String filename = filenameList.get(i);

            //构建输入流
            BufferedInputStream bis= new BufferedInputStream(new ByteArrayInputStream(content));

            //创建文件(zip里面的文件)
            ZipEntry entry = new ZipEntry(filename);
            //放入文件
            zos.putNextEntry(entry);
            //写入文件
            IOUtils.copy(bis,zos);
            //关闭流
            bis.close();
        }

        zos.closeEntry();
        zos.close();
        //设置返回信息
        response.setHeader("Content-Length", String.valueOf(output.size()));
        IOUtils.copy(new ByteArrayInputStream(output.toByteArray()), response.getOutputStream());

        //创建完压缩文件后关闭流
        cos.close();
        output.close();


    }
}

 

你可能感兴趣的:(Java打包下载zip文件)