我使用此代码使用户能够下载zip文件:
if(file_exists($filename)){
header("Content-Disposition: attachment; filename=".basename(str_replace(' ', '_', $filename)));
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
header("Content-Description: File Transfer");
header("Content-Length: " . filesize($filename));
flush();
$fp = fopen($filename, "r");
while (!feof($fp))
{
echo fread($fp, 65536);
flush();
}
fclose($fp);
exit;
}
下载文件时,它仅下载 25,632 KB 的数据。但是zip文件是26,252千字节...
为什么浏览器得到全部 25MB 但随后停止?
我检查了Content-Length
标题以确保它是正确的,它是......
编辑
在 Firefox 中,当我下载文件时,它说"25mb",所以浏览器认为 25mb 是完整的数量......但是,回声时的内容长度26252904?
代码之前添加这个
ob_clean();
ob_end_flush();
您的header('Content-Type ...)
调用毫无用处,因为只有最后一个会发送到浏览器。
下载由 Content-Disposition: attachment
触发。如果要发送 zip 文件,则应发送实际Content-Type: application/zip
。
最后,读取循环是不必要的。
将它们放在一起,您的代码应如下所示:
if (file_exists($filename)) {
$quoted_filename = basename(addcslashes($filename, "'0..'37'"'177"));
header("Content-Disposition: attachment; filename='"{$quoted_filename}'"");
header('Content-Type: application/zip');
header('Content-Length: '.filesize($filename));
readfile($filename);
}
使用单个 MIME 类型来表示数据。
在这种情况下,使用 application/octet-stream
就可以了。这是您事先不知道MIME的时候。当你知道它时,你必须把它放出来。不要使用多个内容类型标头。
通常,当浏览器不知道如何处理特定的MIME时,它将触发下载过程。此外,使用Content-disposition: Attachment; ..
可以确保它。
存在一个简单的readfile($filename)
它将文件的字节发送到请求进程,如下所示:
header("Content-disposition: attachment;filename=" . basename($filename);
readfile($filename);
我也有类似的问题。该文件在火狐中下载正常,但在IE中则不然。似乎Apache正在压缩文件,而IE无法解压缩,因此文件已损坏。解决方案是在 Apache 中禁用 gzipping。您还可以检查 PHP 是否没有即时 gzip 并禁用它。对于 Apache,您可以尝试:
SetEnv no-gzip 1
对于 PHP,在 .htaccess 中:
php_flag zlib.output_compression on
这个答案绝不是一个真正的答案。
但是我确实让它工作了...我只是将内容长度设置为 30000000。因此,它认为文件比实际大,然后下载所有文件。
我知道丑陋的黑客,但我找不到任何其他方法