php下载大型文件失败


php download fails on large files

我正在尝试获得一个下载文件的链接,而无需重定向,或者使用另一个文件下载大型zip文件。

它适用于大约100mb以下的文件,但任何更大的文件,它都会被发送到chrome中的错误页面,上面写着:Error code: ERR_INVALID_RESPONSE

使用jQuery将$file和$path放入一个表单中,然后调用$('form').submit();

function downloadFile($file, $path){
        set_time_limit(0);
        $fullPath = $path . $file;
        if ($fd = fopen ($fullPath, "r")) {

            $fsize = filesize($fullPath);
            $path_parts = pathinfo($fullPath);

            $ext = strtolower($path_parts["extension"]);
            switch ($ext) {
                case "pdf":
                header("Content-type: application/pdf"); // add here more headers for diff. extensions
                header("Content-Disposition: attachment; filename='"".$path_parts["basename"]."'""); // use 'attachment' to force a download
                break;
                default;
                header("Content-type: application/octet-stream");
                header("Content-Disposition: filename='"".$path_parts["basename"]."'"");
            }
            header("Content-length: $fsize");
            header("Cache-control: private"); //use this to open files directly
            while(!feof($fd)) {
                $buffer = fread($fd, 2048);
                echo $buffer;
            }
        }
        fclose ($fd);
        exit;
    }

你知道为什么它在更大的文件上失败了吗?

更新:当我使用以下代码时,它会下载文件,但由于某些原因,完成的文件已损坏,因此无法打开:

set_time_limit(0);
ini_set('memory_limit', '1024M');
// http headers for downloads
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename='"".$filename."'"");
header("Content-Transfer-Encoding: binary");
header("Content-Length: ".$file_size);
ob_end_flush();
@readfile($fileinfo['path']);   

当我使用这个代码时,它只下载第一个49.7kb,然后说它完成了,我甚至一起尝试了ob_flush()flush()

    // http headers for downloads
    header("Pragma: public");
    header("Expires: 0");
    header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
    header("Cache-Control: public");
    header("Content-Description: File Transfer");
    header("Content-type: application/octet-stream");
    header("Content-Disposition: attachment; filename='"".$filename."'"");
    header("Content-Transfer-Encoding: binary");
    header("Content-Length: ".filesize($fileinfo['path']));
    if ($fd = fopen ($fileinfo['path'], "r")) {
            set_time_limit(0);
            ini_set('memory_limit', '1024M');
        while(!feof($fd)) {
            echo fread($fd, 4096);
            flush();
        }   
    }

我在下载程序中唯一做的不同是Content-Transfer-Encoding: chunked。还要将flush()从循环中取出,并确保在发送数据之前执行ob_clean(); flush();,在发送数据之后执行ob_end_flush();