雖然php 中的header()函數(shù)下載文件不支持?jǐn)帱c續(xù)傳功能但有時我們還真需要此功能,如我們下載txt,圖片文件時如果直接是個連接估計是直接打開了而不是下載了,那么我們可如何實現(xiàn)下載呢,代碼如下:
- <?php
- /**
- * 文件下載
- *
- **/
- header("Content-type:text/html;charset=utf-8");
- download('web/www.companysz.com .txt', 'txt文件下載');
- function download($file, $down_name){
- $suffix = substr($file,strrpos($file,'.')); //獲取文件后綴
- $down_name = $down_name.$suffix; //新文件名,就是下載后的名字
- //判斷給定的文件存在與否
- if(!file_exists($file)){
- die("您要下載的文件已不存在,可能是被刪除");
- }
- $fp = fopen($file,"r");
- $file_size = filesize($file);
- //下載文件需要用到的頭
- header("Content-type: application/octet-stream");
- header("Accept-Ranges: bytes");
- header("Accept-Length:".$file_size);
- header("Content-Disposition: attachment; filename=".$down_name);
- $buffer = 1024;
- $file_count = 0;
- //向瀏覽器返回數(shù)據(jù)
- while(!feof($fp) && $file_count < $file_size){
- $file_con = fread($fp,$buffer);
- $file_count += $buffer;
- echo $file_con;
- }
- fclose($fp);
- }
- ?>
新聞熱點
疑難解答