一個關於php將資源提供進行下載的操作類
阿新 • • 發佈:2019-01-05
最近專案有需求需要定期svn更新專案,並打包成下載包供下載,參考了網上的一些相關程式碼後寫了如下一個用來提供給使用者下載的小元件
關於php進行svn操作的元件:http://blog.csdn.net/meeeen7/article/details/78297063
關於php進行zip打包的元件:http://blog.csdn.net/meeeen7/article/details/78297467
class downloadUtil { protected $_filename; protected $_filepath; protected $_filesize; //檔案大小 public function __construct($filepath,$filename){ $this->_filename=$filename; //$this->_filepath=dirname(dirname(dirname(dirname(dirname(__FILE__))))).'/'.$filename; $this->_filepath=$filepath; } //獲取檔名 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 "<script>alert('對不起,您要下載的檔案不存在');</script>"; } } }
使用時直接new downloadUtil()將要下載檔案路徑和檔名傳入建構函式中,其中getfiles函式中的buffer代表了下載時每次傳輸的資料量,可自行進行調節