详细信息 您现在的位置是:首页 > php
ZipArchive实现php打包下载文件
来源:
发布时间:2022-04-14
709 人已围观
摘要php打包下载文件是常见的需求,尤其下载用户资料、二维码等含中文文件名。选择我们需要的文件,打包下载到本地电脑。php自带的ZipArchive类可以非常方便的实现服务器文件打包下载
你还在一个一个下载服务器上文件吗?php自带的ZipArchive类打包下载文件、打包下载服务器各类文件。支持中文文件名。
/** * 下载图片并生成压缩包 * @throws Exception */ function downloadZipImg(){ //要下载文件 $picAllArr = ['domain/张3.png','domain/李4.png']; $tmpDir = 'download/';//压缩包存放路径 if (!file_exists($tmpDir)) { mkdir($tmpDir, 0777, true); } $zipName = date('His') . mt_rand(1000, 9999) . '.zip'; //压缩包文件名 $zipNameUrl = $tmpDir . $zipName; //文件路径 //生成文件 $zip = new \ZipArchive(); if ($zip->open($zipNameUrl, \ZipArchive::OVERWRITE) !== true) { //OVERWRITE 参数会覆写压缩包的文件 文件必须已经存在 if ($zip->open($zipNameUrl, \ZipArchive::CREATE) !== true) { // 文件不存在则生成一个新的文件 用CREATE打开文件会追加内容至zip throw new \Exception('下载失败,文件夹不存在'); } } foreach($picAllArr as $file){ $picName = explode('/',$file)[1]; $basename = $picName.$suffix; //判断图片是否存在 $isFile = file_exists($file); if(!$isFile){ continue; } //抓取图片内容 $fileContent = file_get_contents($file); //添加图片 $zip->addFromString($basename, $fileContent); } $zip->close(); //没有文件 if (!file_exists($zipNameUrl)) { throw new \Exception('下载失败,图片不存在或无法下载'); } header("Cache-Control: public"); header("Content-Description: File Transfer"); header('Content-disposition: attachment; filename=' . $zipName); //文件名 header("Content-Type: application/zip"); //zip格式的 header("Content-Transfer-Encoding: binary"); //告诉浏览器,这是二进制文件 header('Content-Length: ' . filesize($zipNameUrl)); //告诉浏览器,文件大小 //下面2步必须要 ob_clean(); flush(); @readfile($zipNameUrl); unlink($zipNameUrl); //删除文件 exit; }
站点信息
- 电话:15226178738
- QQ:1697915848
- 邮箱:1697915848@qq.com