方法一,采用fread()函数切片下载,适合大流量下载。可以限速下载,但容易导致内存溢出,下载失败。
public function fileUrl($url) { $file = 'uploads/files/'.$url; if (file_exists(\dirname(__FILE__).$file)) { return $this->error("文件不存在"); } // 新文件名 $filename = explode('.', $file); $filename = array_pop($filename); $filename = time().'.'.$filename; //下载文件 $filesize = filesize($file) + 1000; header('Content-Description:File Transfer'); header("Content-Type:application/octet-stream"); header('Content-Transfer-Encoding:binary'); header("Accept-Ranges: bytes"); header('Expires:0'); header('Cache-Control:must-revalidate'); header('Pragma:public'); header("Content-Length:".$filesize); header("Content-Disposition:attachment;filename=".$filename); $fp = fopen($file, "rb"); fseek($fp,0); while (!feof($fp)) { set_time_limit(0); print (fread($fp, 1024 * 8)); flush(); ob_flush(); } fclose($fp); exit (); }
方法二,不限速不切片无限制的形势下载,适合小文件下载。
public function fileUrl2($url) { $file = 'uploads/files/'.$url; if (file_exists(\dirname(__FILE__).$file)) { return $this->error("文件不存在"); } // 新文件名 $filename = explode('.', $file); $filename = array_pop($filename); $filename = time().'.'.$filename; header('Content-type:application/octet-stream'); header('Content-Disposition:attachment;filename='.$filename); header('Content-Length:'.filesize($file)); readfile($file); }