首先,將FileToZip.class檔案放到ThinkPHP/Extend/Library/ORG/Util/檔案夾中,FileToZip.class.php為zip下載類,其詳細代碼如下:
<?php/** * zip下載類檔案 * 遍曆目錄,打包成zip格式 */class traverseDir{ public $currentdir;//目前的目錄 public $filename;//檔案名稱 public $fileinfo;//用於儲存目前的目錄下的所有檔案名稱和目錄名以及檔案大小 public $savepath; public function __construct($curpath,$savepath){ $this->currentdir=$curpath;//返回目前的目錄 $this->savepath=$savepath;//返回目前的目錄 } //遍曆目錄 public function scandir($filepath){ if (is_dir($filepath)){ $arr=scandir($filepath); foreach ($arr as $k=>$v){ $this->fileinfo[$v][]=$this->getfilesize($v); } }else { echo ""; } } /** * 返迴文件的大小 * * @param string $filename 檔案名稱 * @return 檔案大小(KB) */ public function getfilesize($fname){ return filesize($fname)/1024; } /** * 壓縮檔(zip格式) */ public function tozip($items){ $zip=new ZipArchive(); $zipname=date('YmdHis',time()); if (!file_exists($zipname)){ $zip->open($savepath.$zipname.'.zip',ZipArchive::OVERWRITE);//建立一個空的zip檔案 for ($i=0;$iaddFile($this->currentdir.'/'.$items[$i],$items[$i]); } $zip->close(); $dw=new download($zipname.'.zip',$savepath); //下載檔案 $dw->getfiles(); unlink($savepath.$zipname.'.zip'); //下載完成後要進行刪除 } }}/** * 下載檔案 * */class download{ protected $_filename; protected $_filepath; protected $_filesize;//檔案大小 protected $savepath;//檔案大小 public function __construct($filename,$savepath){ $this->_filename=$filename; $this->_filepath=$savepath.$filename; } //擷取檔案名稱 public function getfilename(){ return $this->_filename; } //擷取檔案路徑(包含檔案名稱) public function getfilepath(){ return $this->_filepath; } //擷取檔案大小 public function getfilesize(){ return $this->_filesize=number_format(filesize($this->_filepath)/(1024*1024),2);//去小數點後兩位 } //下載檔案的功能 public function getfiles(){ //檢查檔案是否存在 if (file_exists($this->_filepath)){ //開啟檔案 $file = fopen($this->_filepath,"r"); //返回的檔案類型 Header("Content-type: application/octet-stream"); //按照位元組大小返回 Header("Accept-Ranges: bytes"); //返迴文件的大小 Header("Accept-Length: ".filesize($this->_filepath)); //這裡對用戶端的彈出對話方塊,對應的檔案名稱 Header("Content-Disposition: attachment; filename=".$this->_filename); //修改之前,一次性將資料轉送給用戶端 echo fread($file, filesize($this->_filepath)); //修改之後,一次只傳輸1024個位元組的資料給用戶端 //向用戶端回送資料 $buffer=1024;// //判斷檔案是否讀完 while (!feof($file)) { //將檔案讀入記憶體 $file_data=fread($file,$buffer); //每次向用戶端回送1024個位元組的資料 echo $file_data; } fclose($file); }else { echo ""; } }}
ThinkPHP中載入zip下載類FileToZip.class.php並實現本地檔案打包下載的功能代碼如下所示:
import('ORG.Util.FileToZip');//引入zip下載類檔案FileToZip// 打包下載$handler = opendir($cur_file); //$cur_file 檔案所在目錄$download_file = array();$i = 0;while( ($filename = readdir($handler)) !== false ) { if($filename != '.' && $filename != '..') { $download_file[$i++] = $filename; }}closedir($handler);$scandir=new traverseDir($cur_file,$save_path); //$save_path zip包檔案目錄$scandir->tozip($download_file);
http://www.bkjia.com/PHPjc/824776.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/824776.htmlTechArticle首先,將FileToZip.class檔案放到ThinkPHP/Extend/Library/ORG/Util/檔案夾中,FileToZip.class.php為zip下載類,其詳細代碼如下: php/** * zip下載類檔案 * 遍...