繁体   English   中英

下载脚本极其缓慢

[英]Downloadscript extremely slowly

我用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;
}

我想缓冲是大文件的问题。 尝试以小块(例如兆字节)读取文件,并在打印每个块后调用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";
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM