我是个初学者。我到处找过,但我不知道为什么通过客户端(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);
我无法想象为什么下载的文件无法打开。它腐败了吗?请对此多加说明。提前谢谢。
经过多次尝试,我发现添加下面显示的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;
}