从服务器下载的文件(使用download.php)将无法打开。为什么?

时间:2015-06-25 06:10:49

标签: javascript php html html5 download

我是初学者。我到处搜索,但我不知道为什么通过客户端(Win 7 Firefox)从服务器下载文件后,我无法打开文件。我试过一个PNG文件和一个MP4文件。下载完成,但文件无法打开。 这是我的剧本;

$dl_file = $_GET['val']; //Verified the full path and the file name gets passed here
$basename = basename($dl_file);
$ext = pathinfo($dl_file, PATHINFO_EXTENSION);
$length   = sprintf("%u", filesize($dl_file));

    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename='.$basename.'');
//manually tried '.$basename.'.PNG' - DID NOT work. How to pass $ext here?
        header('Content-Transfer-Encoding: binary');
        header('Connection: Keep-Alive');
        header('Expires: 0');
        header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
        header('Pragma: public');
        header('Content-Length: ' . $length);

        set_time_limit(0);
        readfile($dl_file);

我无法想象为什么下载的文件无法打开。它腐败了吗? 请多说清楚。先感谢您。

1 个答案:

答案 0 :(得分:2)

经过多次尝试,我发现添加下面显示的2行代码(ob_clean和flush)(和/或添加precheck,postcheck参数) - 适用于所有浏览器。谢谢。

if (file_exists($dl_file)) {
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename="'.basename($dl_file).'"' );
    header('Expires: 0');
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
    header('Pragma: public');
    header('Content-Length: ' . filesize($dl_file));
    ob_clean();
    flush();
    readfile($dl_file);
    exit;
}