java 打压缩包浏览器下载

本文介绍了一种在浏览器环境下利用Java技术,通过`HttpServlet`和`ZipOutputStream`实现文件打包下载的方法。通过将多个文件压缩成一个ZIP文件,解决批量文件的下载问题,同时处理了文件名中的空格和编码问题。
摘要由CSDN通过智能技术生成

存一波打包代码

参考博文:https://blog.csdn.net/ajax_mck/article/details/111320900

 /**
     * @param title    压缩包 title
     * @param response
     * @param fileList 文件集合
     * @return
     * @Title downFileZip
     * @Description: 浏览器批量下载文件打包
     * @throws:
     * 思路:先生成多个文件存至虚拟路径,然后调用此方法,最后再删除生成的多个文件
     */
    public boolean downFileZip(String title, HttpServletResponse response, List<File> fileList) throws UnsupportedEncodingException {

        boolean flag = true;
        response.reset();
        response.setContentType("multipart/form-data");
        //设置压缩包名
        String strZipPath = "压缩包";
        strZipPath = URLEncoder.encode(strZipPath + ".zip", "UTF-8");
        //处理文件名空格转加号
        strZipPath = strZipPath.replace("+", "%20");
        // 文件头,不同浏览器需要处理乱码
        response.setHeader("Content-disposition", "attachment;filename="
                + strZipPath);

        try (
                ZipOutputStream zipOutputStream = new ZipOutputStream(new BufferedOutputStream(response.getOutputStream()));
                DataOutputStream os = new DataOutputStream(zipOutputStream)
        ) {
            zipOutputStream.setMethod(ZipOutputStream.DEFLATED);
            //设置conkie关闭进度条显示
            //CommonUtil.setResponseCookie(response);
            if (!CollectionUtils.isEmpty(fileList)) {
                for (File file : fileList) {
                    zipOutputStream.putNextEntry(new ZipEntry(file.getName()));
                    FileInputStream fis = new FileInputStream(file);
                    int len;
                    byte[] b = new byte[1024];
                    while ((len = fis.read(b)) != -1) {
                        os.write(b, 0, len);
                    }
                    fis.close();
                }
            }
        } catch (Exception e) {
            logger.error("压缩失败", e);
            flag = false;
        }
        return flag;
    }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值