赞
踩
通用组合数据代码
- public void downloadZip(HttpServletResponse response) {
- List<ExportData> dataList= new ArrayList<>();
- //开始压缩导出
- String fileName = "download.zip";
- response.reset();
- response.setCharacterEncoding("UTF-8");
- response.setContentType("application/octet-stream");
- response.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes(StandardCharsets.UTF_8), "ISO8859-1"));
- response.setHeader("Access-Control-Allow-Origin", "*");
- byte[] dataByteArr;
- if (CollectionUtil.isNotEmpty(dataList)) {
- try {
- dataByteArr = zipFile(dataList);
- response.getOutputStream().write(dataByteArr);
- response.flushBuffer();
- } catch (Exception e) {
- log.error("压缩zip数据出现异常", e);
- e.printStackTrace();
- }
- }
- }

压缩文件
- /**
- * zip文件
- *
- * @param dataList 数据列表
- * @return {@link byte[]}
- */
- public byte[] zipFile(List<ExportData> dataList) throws IOException {
- // 将字节写到一个字节输出流里
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- try (ZipOutputStream out = new ZipOutputStream(baos)) {
- // 创建zip file in memory
- for (ExportData data: dataList) {
- ZipEntry entry = new ZipEntry("文件名.doc");
- out.putNextEntry(entry);
- out.write(data.getContent().getBytes(StandardCharsets.UTF_8));
- out.closeEntry();
- }
- baos.close();
- } catch (IOException e) {
- log.error("压缩zip数据出现异常", e);
- throw new RuntimeException("压缩zip包出现异常");
- } finally {
- baos.close();
- }
- return baos.toByteArray();
- }

前端代码 请求接口带上"blob"
responseType: "blob",
res就是后端返回的流
- const blob = new Blob([res], { type: "application/zip" });
- const fileName = `批量下载`;
- if ("download" in document.createElement("a")) {
- // 非IE下载
- const elink = document.createElement("a");
- elink.download = fileName;
- elink.style.display = "none";
- elink.href = window.URL.createObjectURL(blob);
- document.body.appendChild(elink);
- elink.click();
- window.URL.revokeObjectURL(elink.href); // 释放URL 对象
- document.body.removeChild(elink);
- } else {
- // IE10+下载
- navigator.msSaveBlob(blob, fileName);
- }

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。