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

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

 

 

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

Array
(
    [0] => E:phpstudy_proWWWsubjectpublicuploadsfiletiantan2022aa.pdf
    [1] => E:phpstudy_proWWWsubjectpublicuploadsfiletiantan2022bb.pdf
    [2] => E:phpstudy_proWWWsubjectpublicuploadsfiletiantan2022cc.pdf
    [3] => E:phpstudy_proWWWsubjectpublicuploadsfiletiantan2022dd.pdf
    [4] => E:phpstudy_proWWWsubjectpublicuploadsfiletiantan2022ee.pdf
    [5] => E:phpstudy_proWWWsubjectpublicuploadsfiletiantan2022ff.pdf
    [6] => E:phpstudy_proWWWsubjectpublicuploadsfiletiantan2022gg.pdf
)

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

代码如下:

$files = ('E:phpstudy_proWWWsubjectpublicuploadsfiletiantan2022aa.pdf','E:phpstudy_proWWWsubjectpublicuploadsfiletiantan2022bb.pdf','E:phpstudy_proWWWsubjectpublicuploadsfiletiantan2022cc.pdf','E:phpstudy_proWWWsubjectpublicuploadsfiletiantan2022dd.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);

 

内容来源于网络如有侵权请私信删除

文章来源: 博客园

原文链接: https://www.cnblogs.com/zxf100/p/17151328.html

你还没有登录,请先登录注册
  • 还没有人评论,欢迎说说您的想法!

相关课程