2013-03-04 64 views
0

我已經用javascript和php編寫了一個下載腳本。它可以工作,但是如果我想下載一個大文件(例如1GB zip文件),那麼它的結束時間太長了。我認爲它有一些事情要做,我讀了這個文件。如果是這樣,任何想法如何讓它更快?
注意事項:我需要一個標題,強制下載原因如圖像,pdf,任何類型的文件類型。下載腳本極其緩慢

JS很簡單。看看這個:

function downloadFile(file){ 
    document.location.href = "script.php?a=downloadFile&b=."+ file; 
} 

PHP很簡單,但:

function downloadFile($sFile){ 
    #Main function 
    header('Content-Type: '.mime_content_type($sFile)); 
    header('Content-Description: File Transfer'); 
    header('Content-Length: ' . filesize($sFile)); 
    header('Content-Disposition: attachment; filename="' . basename($sFile) . '"'); 
    readfile($sFile); 
} 

switch($_GET['a']){ 

    case 'downloadFile': 
     echo downloadFile($_GET['b']); 
     break; 
} 
+1

你可以從你的交換機到downloadFile中的回聲,而不是讀取一氣呵成整個文件,塊,這也使一次讀取和回放一小部分文件。 – NickSlash 2013-03-04 14:35:37

回答

3

我猜緩衝對大文件的問題。 嘗試以小塊(如兆字節)讀取文件,並在打印每個塊後調用flush函數來刷新輸出緩衝區。

編輯:嗯,好吧,這裏的代碼示例,你應該嘗試:

function downloadFile($sFile){ 
    #Main function 

    if ($handle = fopen($sFile, "rb")) { 
     header('Content-Type: '.mime_content_type($sFile)); 
     header('Content-Description: File Transfer'); 
     header('Content-Length: ' . filesize($sFile)); 
     header('Content-Disposition: attachment; filename="' . basename($sFile) . '"'); 

     while (!feof($handle)) { 
      print fread($handle, 1048576); 
      flush(); 
     } 
     fclose($handle); 
    } else { 
     header('Status: 404'); 
     header('Content-Type: text/plain'); 
     print "Can't find the requested file"; 
    } 
} 
+0

我真的很想使用瀏覽器下載。如果我打開www.example.com/some.zip,瀏覽器會自動啓動以下載文件。是否沒有機會使用任何擴展名文件(圖片,PDF文件,..?)來下載這個強制文件?還是我必須用塊文件發回一個文件頭? – Sylnois 2013-03-04 15:22:19

+0

呃,什麼?我已經用一個你應該嘗試的例子更新了答案。 – JackTheRandom 2013-03-04 16:44:03