【Java文件下载压缩包】Zip输出流处理,实现下载批量文件为压缩包格式

假如程序猿们需要做一个批量把后台[本地/第三方]文件汇总在压缩包内并返回给前端下载,这里是一个测试成功的Demo,可以放心使用。

//控制层
@RequestMapping(value = "/downloadZip", method = RequestMethod.GET)
public ResponseEntity<byte[]> downloadZip(@RequestBody DownloadVo downloadVo) {
    return downloadService.downloadZip(downloadVo);
}
//服务层
import java.nio.file.Path;
import java.io.File;
import java.io.ByteArrayOutStream;
import java.io.BufferedOutputStream;
import java.util.zip.ZipOutputStream;


poblic ResponseEntity<byte[]> downloadZip(DownloadVo downloadVo) throws IOException {
    
    //...
    
    ByteArrayOutStream byteArrayOutStream = new ByteArrayOutStream();
    try(BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(byteArrayOutStream);
       ZipOutputStream zos = new ZipOutputStream(bufferedOutputStream);){
        //假如你有存储批量文件信息的一个列表
        List<DocumentList> docList = docDao.getDocumentListByParam(downloadVo);//DocumentList,docDao 自行定义即可

        for(DocumentList ele : docList) {
             if(...){ //第一种情况:假如你会掉第三方获取一个byte[]数据
                byte[] document  = getByteDocument(downloadVo);

                populateDocumentToZip(zos,ele.getFileName,document);
             } else (...) {//第二种情况:假如你会调本地,获取一个File类型的文件

                File targetFile = new File(ele.getFilePath);//有必要的话,这一行需要做一个识别正确文件路径的方法
                if(!targetFile.exists()) {
                    continue;
                }
                 Path path = targetFile.toPath();
                 populateDocumentToZip(zos,ele.getFileName,Files.readAllBytes(path);
             }
        }
    }catch(IOException e) {
        logger.info(e);
    }finally {
        byteArrayOutStream.close();
    }
    
    //....
   
}


public void populateDocumentsToZip(ZipOutputSteam zos,String fileName, byte[] document) {
	try{
        zos.putNextEntry(new ZipEntry(fileName));
        zos.write(document);
    }catch(Exception e) {
        logger.error(e);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值