java代码实现打包下载

主代码

@Override
public void downloadPayAgre(HttpSession session, HttpServletResponse response, HttpServletRequest request,
                            String realName) {
    ZipOutputStream zos = null;
    try {
        String zipFilePath = "压缩包" + ".zip";
        response.reset();
        response.setCharacterEncoding("gb2312");
        response.setHeader("Content-Disposition", "attachment; filename=" + new String(zipFilePath.getBytes("UTF8"), "ISO-8859-1"));
        zos = new ZipOutputStream(response.getOutputStream());
        //查询文件信息
        EcPayAgre ctPayAgre = ecPayAgreDao.findByRealName(realName);
        addZip("", ctPayAgre.getRealName(),ctPayAgre.getSuffix(), ctPayAgre.getFileName(), zos);
        //查询文件信息
        EcPayFile ecPayFile = ecPayFileDao.findByCtpaId(ctPayAgre.getCtpaId());
        addZip("", ecPayFile.getRealName(),ecPayFile.getSuffix(), ecPayFile.getFileName(), zos);
    }catch (Exception e){
        e.printStackTrace();
    }finally {
        try {
            zos.flush();
            zos.close();
        }catch (Exception e){
            System.out.println("文件压缩失败");
        }
    }
}

1、esponse.setHeader(“Content-Disposition”, “attachment; filename=” + new String(zipFilePath.getBytes(“UTF8”), “ISO-8859-1”));这里的UTF8编码,在ie浏览器中压缩包名称有可能是乱码,可将其改变为GBK,就可以解决。
2、addZip("", ctPayAgre.getRealName(),ctPayAgre.getSuffix(), ctPayAgre.getFileName(), zos);第一个参数为空,则直接将文件放入压缩包中,“图片/”在压缩包中新建一个名为"图片"的文件夹,并将文件放入其中。第二个参数是文件在文件服务器上的名称,第三个参数是后缀名,第四个参数是文件名称。

调用方法

private void addZip(String path, String realName,String suffix,String fileName, ZipOutputStream zos) throws Exception{
    if(realName==null||realName.equals("")){
        return;
    }
    byte[] data=downloadFile(realName+"."+suffix);
    zos.putNextEntry(new ZipEntry(fileName+"."+suffix));
    if(data==null){
        throw new BusinessException(fileName+"."+suffix+"下载失败");
    }
    zos.write(data);
    zos.closeEntry();
}

//下载文件
private byte[] downloadFile(String realName){
    AttachmentBean bean = new AttachmentBean();
    bean.setFileName(realName);
    IAttachmentService downAttachmentService  = ExcectorAttachmentFacatory.getInstance().createDownService(bean);
    downAttachmentService.setAttachmentBean(bean);
    try{
        Message message = downAttachmentService.execute();
        if(message.isResult()) {
            byte[] fileData = Base64.decodeBase64((String) message.getData());
            byte[] data = GzipUtil.uncompress(fileData);
            return data;
        }else{
            System.out.println("文件下载失败");
            return null;
        }
    }catch (Exception e){
        System.out.println("文件下载失败");
        return null;
    }

}

文件下载根据需要更改

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值