Zac*_*ac1 1 html javascript php 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);
Run Code Online (Sandbox Code Playgroud)
我无法想象为什么下载的文件无法打开。是否腐败?请对此进行更多说明。先感谢您。
经过多次尝试,我发现添加下面所示的两行代码(ob_clean和flush)(和/或添加预检查、后检查参数) - 在所有浏览器上都有效。谢谢。
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;
}
Run Code Online (Sandbox Code Playgroud)