简体   繁体   English

下载脚本极其缓慢

[英]Downloadscript extremely slowly

I've written a download script with javascript and php. 我用javascript和php编写了一个下载脚本。 It works, but if i want to download a large file(example 1GB zip file) it has tooo long to end up with the request. 它可以工作,但是如果我要下载一个大文件(例如1GB的zip文件),它的时间太长了,无法完成请求。 I think it has something to do, that i read the file. 我认为这与我读取文件有关。 If it's this, any idea how to get it faster? 如果是这样,您知道如何更快地获取它吗?
Notice : I need a header, cause of force downloading like images, pdfs, any kind of filetype. 注意 :我需要一个标头,以强制下载图像,pdf,任何类型的文件类型的原因。

JS is very simple. JS很简单。 Look at this: 看这个:

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

PHP is simple yet: 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;
}

I guess buffering is the issue for the large files. 我想缓冲是大文件的问题。 Try reading your file in small chunks (like a megabyte) and call flush function to flush the output buffer after printing each chunk. 尝试以小块(例如兆字节)读取文件,并在打印每个块后调用flush函数以刷新输出缓冲区。

EDIT: eh, okay, here's the code example you should try: 编辑:嗯,好的,这是您应该尝试的代码示例:

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