header('Content-type:application/octet-stream')导致0字节文件

Ako*_*kos 6 php download

我在PHP中使用数据库查询来检索二进制文件.但是当我试图强制下载它时,标题('Content-type:application/octet-stream')行会导致0字节文件.如果没有该行,我可以下载包含完整内容的文件.这是一个肯定的二进制文件,所以我无法理解为什么该行会导致问题.代码:

$result = mysql_query("SELECT data FROM stored_file WHERE file_name = '$q'");

while($row = mysql_fetch_array($result))
{
    $file = $row['data'];
}


    header('Content-disposition: attachment; filename='.$q);
    header('Content-type: application/octet-stream');
    header('Content-Length: '.filesize($file));
    header("Pragma: no-cache");
    header("Expires: 0");
    echo $file;
Run Code Online (Sandbox Code Playgroud)

任何的想法?谢谢.

mar*_*rio 5

filesize() 不会返回有意义的值.

您有二进制数据$file,而不是第一个参数所需的实际文件名.因此你会得到一个错误.(启用error_reporting!没有看到错误,没有它们是两回事.)

那么你想要使用的是strlen($file),而不是filesize().

顺便说一句,application/octet-stream或其他填写没有用于强制下载.这Content-Disposition:是最重要的标题.您仍然可以发送正确的MIME类型.