我正在尝试使用 php 标头和 readfile 函数强制下载,这是我的代码:
if(file_exists($file_url)){header('Content-Type: '.$ftype);
header('Content-Transfer-Encoding: binary');
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header("Content-Length: " . filesize($dir.$fname));
header("Content-disposition: attachment; filename=\"".$fname."\"");
ob_clean();
flush();
readfile($dir.$fname);
exit;}
问题是大于 37mb 的文件以 0 字节下载。我检查了 php 配置并memory_limit
设置为 200mb,我尝试用这个块下载:
$filename = $dir.$fname;
$filesize = filesize($filename);
$chunksize = 4096;
if($filesize > $chunksize)
{
$srcStream = fopen($filename, 'rb');
$dstStream = fopen('php://output', 'wb');
$offset = 0;
while(!feof($srcStream)) {
$offset += stream_copy_to_stream($srcStream, $dstStream, $chunksize, $offset);
}
fclose($dstStream);
fclose($srcStream);
}
else
{
// stream_copy_to_stream behaves() strange when filesize > chunksize.
// Seems to never hit the EOF.
// On the other handside file_get_contents() is not scalable.
// Therefore we only use file_get_contents() on small files.
echo file_get_contents($filename);
}
但不是强制下载,而是显示文件。有任何想法吗?