前言
本文主要給大家介紹的是關于PHP/ThinkPHP實現(xiàn)批量打包下載文件的相關內(nèi)容,分享出來供大家參考學習,話不多說了,來一起看看詳細的介紹:
需求描述:
有數(shù)個文件,包含圖片,文檔。需要根據(jù)條件自動打包成壓縮包,提供下載。
解決(ZipArchive 類):
PHP提供了ZipArchive 類可為我們實現(xiàn)這一功能,demo:
<?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);
區(qū)別在引用的時候路徑要對,結(jié)束。
相關參考:
http://www.php.net/manual/zh/class.ziparchive.php
http://dengrongguan12.github.io/blog/2016/php-ziparchive/
總結(jié)
好了,大概就這樣,以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學習或者工作能帶來一定的幫助,如果有疑問大家可以留言交流,謝謝大家對的支持
【網(wǎng)站聲明】本站除付費源碼經(jīng)過測試外,其他素材未做測試,不保證完整性,網(wǎng)站上部分源碼僅限學習交流,請勿用于商業(yè)用途。如損害你的權(quán)益請聯(lián)系客服QQ:2655101040 給予處理,謝謝支持。