0

我正在尝试使用 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);
    }

但不是强制下载,而是显示文件。有任何想法吗?

4

2 回答 2

1
function readfile_chunked($filename,$retbytes=true) { 
   $chunksize = 1*(1024*1024); // how many bytes per chunk 
   $buffer = ''; 
   $cnt =0; 
   // $handle = fopen($filename, 'rb'); 
   $handle = fopen($filename, 'rb'); 
   if ($handle === false) { 
       return false; 
   } 
   while (!feof($handle)) { 
       $buffer = fread($handle, $chunksize); 
       echo $buffer; 
       ob_flush(); 
       flush(); 
       if ($retbytes) { 
           $cnt += strlen($buffer); 
       } 
   } 
       $status = fclose($handle); 
   if ($retbytes && $status) { 
       return $cnt; // return num. bytes delivered like readfile() does. 
   } 
   return $status; 
}
header('Content-Type: '.$ftype);
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."\""); 
readfile_chunked($filen);
于 2012-07-12T16:07:16.640 回答
0

试试这个。

header ("Content-Disposition: attachment; filename=".$filename."\n\n");
header ("Content-Type: application/octet-stream");
@readfile($link); // Path to file
于 2012-07-12T15:54:48.520 回答