SpringBoot实现多文件压缩下载.zip

前言:服务器生成多个文本文件。需要打包一次返回下载。例如:xml,word,excel

        try {
            response.setHeader("Content-Disposition", "attachment;filename=" + new String("压缩包名称.zip".getBytes("GB2312"), "ISO-8859-1"));  // 需要编码否则中文乱码
            response.setContentType("application/zip;charset=utf-8");
            response.setCharacterEncoding("UTF-8");

            // 输出流直接用ZipOutputStream包裹,这样直接输出压缩后的流。减少服务器生成压缩文件步骤。
            ZipOutputStream zipOutputStream = new ZipOutputStream(response.getOutputStream());

            ZipEntry zipEntryXtv = new ZipEntry("第一个文件名.xml");
            zipOutputStream.putNextEntry(zipEntryXtv);
            zipOutputStream.write(xml.getBytes());

            ZipEntry zipEntryDel = new ZipEntry("第二个文件名.xml");
            zipOutputStream.putNextEntry(zipEntryDel);
            zipOutputStream.write(xmlDel.getBytes());

            zipOutputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

你可能感兴趣的:(Spring,Boot)