PHP使用ZipArchive批量打包压缩文件并下载

PHP使用ZipArchive批量打包压缩文件,并下载。使用php自带的ZipArchive类,可以压缩或解压文件。

首先需要确定已经安装了zip扩展,如果没有安装,请先安装,下载:http://pecl.php.net/package/zip (相应php版本的zip包)

 

 

先把需要下载的文件路径找出来并组成数组,如下

复制代码
Array
(
    [0] => E:\phpstudy_pro\WWW\subject\public\uploads\file\tiantan\2022\aa.pdf
    [1] => E:\phpstudy_pro\WWW\subject\public\uploads\file\tiantan\2022\bb.pdf
    [2] => E:\phpstudy_pro\WWW\subject\public\uploads\file\tiantan\2022\cc.pdf
    [3] => E:\phpstudy_pro\WWW\subject\public\uploads\file\tiantan\2022\dd.pdf
    [4] => E:\phpstudy_pro\WWW\subject\public\uploads\file\tiantan\2022\ee.pdf
    [5] => E:\phpstudy_pro\WWW\subject\public\uploads\file\tiantan\2022\ff.pdf
    [6] => E:\phpstudy_pro\WWW\subject\public\uploads\file\tiantan\2022\gg.pdf
)
复制代码

逻辑:先把文件压缩到指定目录(自定义$addonFile目录下),然后再把文件输出下载

代码如下:

复制代码
$files = ('E:\phpstudy_pro\WWW\subject\public\uploads\file\tiantan\2022\aa.pdf','E:\phpstudy_pro\WWW\subject\public\uploads\file\tiantan\2022\bb.pdf','E:\phpstudy_pro\WWW\subject\public\uploads\file\tiantan\2022\cc.pdf','E:\phpstudy_pro\WWW\subject\public\uploads\file\tiantan\2022\dd.pdf');

// 压缩文件名
$addonFile = ROOT_PATH.'public'.DS.'uploads'.DS.'downzip'.DS.'学科评估_【'.$info['hospital'].'_'.$this->year. '年】.zip';
$zip = new \ZipArchive;

//新建zip压缩包
$zip->open($addonFile,\ZipArchive::CREATE | \ZipArchive::OVERWRITE);
//把文件一张一张加进去压缩
foreach ($files as $key => $value) {
    $zip->addFile($value,basename($value));
}
//打包zip
$zip->close();

header("Cache-Control: public"); 
header("Content-Description: File Transfer"); 
header('Content-disposition: attachment; filename='.basename($addonFile)); //文件名 
header("Content-Type: application/force-download");
header("Content-Transfer-Encoding: binary");
header('Content-Length: '. filesize($addonFile)); //告诉浏览器,文件大小 
readfile($addonFile);
复制代码

 

posted @   下页、再停留  阅读(487)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示