前言
本文主要給大家介紹的是關于PHP/ThinkPHP實現批量打包下載文件的相關內容,分享出來供大家參考學習,話不多說了,來一起看看詳細的介紹:
需求描述:
有數個文件,包含圖片,文檔。需要根據條件自動打包成壓縮包,提供下載。
解決(ZipArchive 類):
PHP提供了ZipArchive 類可為我們實現這一功能,demo:
php;"><?php $files = array('image.jpeg','text.txt','music.wav');$zipname = 'enter_any_name_for_the_zipped_file.zip';$zip = new ZipArchive;$zip->open($zipname, ZipArchive::CREATE);foreach ($files as $file) { $zip->addFile($file);}$zip->close(); ///Then download the zipped file.header('Content-Type: application/zip');header('Content-disposition: attachment; filename='.$zipname);header('Content-Length: ' . filesize($zipname));readfile($zipname); ?>
ThinkPHP版
$zip = new /ZipArchive;//壓縮文件名$filename = 'download.zip';//新建zip壓縮包$zip->open($filename,/ZipArchive::OVERWRITE);//把圖片一張一張加進去壓縮foreach ($images as $key => $value) { $zip->addFile($value);}//打包zip$zip->close(); //可以直接重定向下載header('Location:'.$filename); //或者輸出下載header("Cache-Control: public"); header("Content-Description: File Transfer"); header('Content-disposition: attachment; filename='.basename($filename)); //文件名 header("Content-Type: application/force-download");header("Content-Transfer-Encoding: binary");header('Content-Length: '. filesize($filename)); //告訴瀏覽器,文件大小 readfile($filename);
區別在引用的時候路徑要對,結束。
相關參考:
http://www.php.net/manual/zh/class.ziparchive.php
http://dengrongguan12.github.io/blog/2016/php-ziparchive/
總結
好了,大概就這樣,以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作能帶來一定的幫助,如果有疑問大家可以留言交流,謝謝大家對VeVb武林網的支持
新聞熱點
疑難解答
圖片精選