下载速度非常慢

时间:2013-03-04 14:24:57

标签: php javascript download

我用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 个答案:

答案 0 :(得分: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";
    }
}