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

字数 33阅读 938

看码是最好的表达:

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

推荐阅读更多精彩内容