Java+Vue导出zip压缩包前后端实现

开发 前端
通过cn.hutool.extra.qrcode.QrCodeUtil生成二维码图片,得到byte[]通过java.util.zip.ZipOutputStream将byte[]写入压缩包通过java.io.ByteArrayOutputStream返回完整的byte[]全部写入完成,得到完整的byte[]输出到HttpServletResponse设置HttpServletResponse响应。

本例实现批量导出二维码图片文件,将所有的图片放在一个zip压缩包中。

实现步骤:

1、查询数据循环生成二维码图片

2、将生成的二维码图片放在一个压缩包中,通过数据流返回给前端

  • 通过cn.hutool.extra.qrcode.QrCodeUtil生成二维码图片,得到byte[]
  • 通过java.util.zip.ZipOutputStream将byte[]写入压缩包
  • 通过java.io.ByteArrayOutputStream返回完整的byte[]
  • 全部写入完成后,得到完整的byte[]输出到HttpServletResponse
  • 设置HttpServletResponse响应头数据,标记为文件下载

3、前端Vue得到数据流实现下载

  • 调用后端接口,设置responseType: 'blob'
  • 通过window.navigator.msSaveBlob下载文件

一、后端接口生成zip压缩文件byte[]

/**
     * 导出二维码
     *
     */
    @RequestMapping(value = "/exportQrcode")
    public void exportQrcode(HttpServletRequest request, HttpServletResponse response, ProQrcode proQrcode) throws IOException {
        // Step.1 组装查询条件
        // ... 此处省略数据查询条件...
  // 查询数据
        List<ProQrcode> list = service.list(queryWrapper);
        int width = 800;
        if (StringUtils.isNotBlank(widthStr)) {
            width = Integer.parseInt(widthStr);
        }
        byte[] data = genQrcodeImg(list, width);
        zip(response, data);
    }
    /**
     * 批量生产图片zip压缩包数据
     * */
    private byte[] genQrcodeImg(List<ProQrcode> list, int width) {
        try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
             ZipOutputStream zip = new ZipOutputStream(outputStream)) {

            for (int i = 0; i < list.size(); i++) {
                ProQrcode qrcode = list.get(i);
                try {
                    // 添加到zip,设置文件名,后缀.png
                    zip.putNextEntry(new ZipEntry(String.format("%d.%s.png", i + 1, qrcode.getCode())));
                    // 查询是否配置了logo,如果有logo,则把logo添加到二维码中
                    BufferedImage logo = CustomerBrandCache.getLogo(qrcode.getCustomerBrandId());
                    QrConfig config = new QrConfig();
                    config.setWidth(width).setHeight(width);
                    if (logo != null) {
                        config.setImg(logo);
                    }
                    // 生成二维码图片
                    byte[] bytes = QrCodeUtil.generatePng(qrcode.getLinkUrl(), config);
                    // 将byte[]写入到压缩包中
                    IOUtils.write(bytes, zip);
                    zip.flush();
                    zip.closeEntry();
                } catch (IOException e) {
                    log.error("addQrcode,error:", e);
                }
            }
            return outputStream.toByteArray();
        } catch (Exception e) {
            log.error("", e);
        }
        return new byte[0];
    }

    /**
     * 生成zip文件,设置响应头为文件下载
     */
    private void zip(HttpServletResponse response, byte[] data) throws IOException {
        response.reset();
        response.addHeader("Access-Control-Allow-Origin", "*");
        response.addHeader("Access-Control-Expose-Headers", "Content-Disposition");
        response.setHeader("Content-Disposition", "attachment; filename=\"qrcode.zip\"");
        response.addHeader("Content-Length", "" + data.length);
        response.setContentType("application/octet-stream; charset=UTF-8");
        IOUtils.write(data, response.getOutputStream());
    }

通过cn.hutool.extra.qrcode.QrCodeUtil生成二维码图片,得到byte[]通过java.util.zip.ZipOutputStream将byte[]写入压缩包通过java.io.ByteArrayOutputStream返回完整的byte[]全部写入完成后,得到完整的byte[]输出到HttpServletResponse设置HttpServletResponse响应头数据,标记为文件下载

二、Vue前端调用后端接口实现下载

/**
 * 导出二维码数据
 */
export const exportQrcode = async (name, params) => {
  const data = await defHttp.get({ url: Api.exportQrcode, params, responseType: 'blob', timeout: 30000 }, { isTransformResponse: false })
  if (!data) {
    createMessage.warning('文件下载失败')
    return
  }
  if (!name || typeof name != 'string') {
    name = '导出文件'
  }
  const blobOptions = { type: 'application/octet-stream' }
  const fileSuffix = '.zip'
  debugger
  if (typeof window.navigator.msSaveBlob !== 'undefined') {
    window.navigator.msSaveBlob(new Blob([data], blobOptions), name + fileSuffix)
  } else {
    const url = window.URL.createObjectURL(new Blob([data], blobOptions))
    const link = document.createElement('a')
    link.style.display = 'none'
    link.href = url
    link.setAttribute('download', name + fileSuffix)
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link) //下载完成移除元素
    window.URL.revokeObjectURL(url) //释放掉blob对象
  }
}

调用后端接口,设置responseType: 'blob'通过window.navigator.msSaveBlob下载文件


责任编辑:武晓燕 来源: 今日头条
相关推荐

2023-05-29 19:17:31

2023-03-29 08:59:59

Go压缩包文档

2023-05-18 22:34:15

2024-01-03 08:20:40

2016-12-14 09:24:42

文件目录压缩

2011-12-30 11:14:41

Javazip

2024-02-27 08:27:18

元素拖拽Vue3拼图验证

2022-04-06 07:50:57

JWT后端Spring

2022-09-01 07:18:21

分离项目Vue

2019-06-12 19:00:14

前后端分离AppJava

2022-09-06 10:26:38

前后端分离Vue跨域

2021-06-16 08:05:14

centos nginx 后端

2023-02-08 16:29:58

前后端开发

2019-04-29 14:51:05

前后端JavaVue.js

2021-01-25 14:10:49

Spring BootVueJava

2018-10-23 14:24:10

2021-09-18 09:45:33

前端接口架构

2021-01-18 08:00:28

微软WindowsWindows 10

2017-10-11 18:17:06

大数据数据可视化前后端

2020-02-13 09:52:48

加密前后端https
点赞
收藏

51CTO技术栈公众号