龙空技术网

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

顽石九变 90

前言:

此刻朋友们对“java 解析zip文件”可能比较珍视,朋友们都想要剖析一些“java 解析zip文件”的相关资讯。那么小编同时在网络上汇集了一些对于“java 解析zip文件””的相关知识,希望各位老铁们能喜欢,各位老铁们快快来学习一下吧!

本例实现批量导出二维码图片文件,将所有的图片放在一个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下载文件

标签: #java 解析zip文件