压缩字节数组成zip包并下载

看码是最好的表达:

public class DownloadFileDto implements Serializable {
    private static final long serialVersionUID = 1L;

    private String fileName = "";
    private byte[] byteDataArr = new byte[0];

    public String getFileName() {
        return fileName;
    }

    public void setFileName(String fileName) {
        this.fileName = fileName;
    }

    public byte[] getByteDataArr() {
        return byteDataArr;
    }

    public void setByteDataArr(byte[] byteDataArr) {
        this.byteDataArr = byteDataArr;
    }

    @Override
    public String toString() {
        return "DownloadFileDto{" +
                "fileName='" + fileName + '\'' +
                ", byteDataArr=" + Arrays.toString(byteDataArr) +
                '}';
    }
}
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.io.output.ByteArrayOutputStream;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

@RestController
public class ZipDownloadController {
    private static final Log logger = LogFactory.getLog(ZipDownloadController.class);

    @RequestMapping(value = "/zipDownload", method = RequestMethod.GET)
    public void downloadZipExcels(HttpServletResponse response) throws Exception {
        List<DownloadFileDto> downloadFileDtoList = null;
        /**获取到文件字节数组*/
//        downloadFileDtoList = fileService.getZipFileContent();

        String fileName = "生成压缩包下载.zip";
        response.reset();
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("UTF-8"), "ISO8859-1"));

        if (CollectionUtils.isNotEmpty(downloadFileDtoList)) {
            try {
                byte[] dataByteArr = zipFile(downloadFileDtoList);
                response.getOutputStream().write(dataByteArr);
                response.flushBuffer();
            } catch (Exception e) {
                logger.error("压缩zip数据出现异常", e);
                throw new RuntimeException("压缩zip包出现异常");
            }
        }
    }

    public byte[] zipFile(List<DownloadFileDto> downloadFileDtoList) throws Exception {
        /**将字节写到一个字节输出流里*/
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ZipOutputStream out = new ZipOutputStream(baos);

        try {
            /**创建zip file in memory */
            for (DownloadFileDto downloadFileDto : downloadFileDtoList) {
                ZipEntry entry = new ZipEntry(downloadFileDto.getFileName());
                entry.setSize(downloadFileDto.getByteDataArr().length);
                out.putNextEntry(entry);
                out.write(downloadFileDto.getByteDataArr());
                out.closeEntry();
            }
        } catch (IOException e) {
            logger.error("压缩zip数据出现异常", e);
            throw new RuntimeException("压缩zip包出现异常");
        } finally {
            if (out != null) {
                out.close();
            }
        }
        return baos.toByteArray();
    }

}

参考链接:
http://memorynotfound.com/create-zip-file-try-resources-java/
https://dzone.com/articles/how-compress-and-uncompress

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • /Library/Java/JavaVirtualMachines/jdk-9.jdk/Contents/Home...
    光剑书架上的书阅读 3,923评论 2 8
  • afinalAfinal是一个android的ioc,orm框架 https://github.com/yangf...
    passiontim阅读 15,507评论 2 45
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,886评论 18 139
  • 今天突然看见了几张插画,好像在心底安放的一杯茶,突然被人打翻了,洒了几滴茶,清香四溢。 一直都喜欢独来独往,有时候...
    小毛驢阅读 245评论 0 1
  • 从爱上一株草开始,爱上一条泥泞路,不是柏油路,也非水泥路,只是一条也许长满野草的小路。爱着野草,也不必小心翼翼,每...
    雨行人阅读 161评论 0 2