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);
——現在的努力,只為小時候吹過的牛逼! ——
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/544931.html
標籤:其他
下一篇:Python中出現IndentationError:unindent does not match any outer indentation level錯誤的解決方法
