作为参考,我已经阅读并尝试了这些和其他几个线程中的答案:
使用 php 创建和提供压缩文件
打开下载的 zip 文件会创建 cpgz 文件吗?
我的服务器上有一个 zip 文件。
当我使用 Filezilla 将该 Zip 文件从我的服务器移动到我的 Mac 时,我可以正常打开它。
当我使用此 PHP 代码将 Zip 文件下载到我的 Linux 计算机时,它可以正常打开。
当我使用此 PHP 代码将 Zip 文件下载到我的 Mac(使用 Safari 或 Firefox)时,我收到一条错误消息,提示“解压失败”或“存档结构已损坏”,或者我收到一个 .cpgz 文件 - 我相信这是意味着计算机正在压缩文件,而不是解压缩文件。
这是我用来交付 zip 文件的 PHP 代码。
$zipname = "myfile.zip";
$zippath = "/path/to/" . $zipname;
if ($downloadzip = fopen ($zippath, "r")) {
$fsize = filesize($zippath);
header("Content-type: application/zip");
header("Content-Disposition: attachment; filename=\"".$zipname."\"");
header("Content-length: $fsize");
header('Content-Transfer-Encoding: binary');
#header("Cache-control: private"); //use this to open files directly
echo fpassthru($downloadzip); // deliver the zip file
}
fclose ($downloadzip);
我发现一些有效的标题。我真的不知道或关心它为什么起作用,我只是很高兴它起作用......我尝试了很多不同的东西,.htaccess 文件,php.ini / zlib 设置。
答案如下http://perishablepress.com/http-headers-file-downloads/
$zipName = 'myfile.zip';
$zipPath = 'mydirectory/' . $zipName;
if (file_exists($zipPath)) {
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=\"".$zipName."\"");
header("Content-Transfer-Encoding: binary");
header("Content-Length: ".filesize($zipPath));
ob_end_flush();
@readfile($zipPath);
}
通常,该问题是由在读出文件之前打印或回显到页面的额外字符引起的。即使有空格也会导致失败。要解决该问题,请致电ob_end_clean();
在读取文件之前,这将清除输出缓冲区并关闭缓冲。
但请记住,您可以拥有nested输出缓冲区,这也会损坏您的下载(欢呼Vladamir为了弄清楚这一点)。因此,要完全清除输出缓冲区,请在读取文件之前运行此命令:
while (ob_get_level()) {
ob_end_clean();
}
这将清除您的整个缓冲区,并且您不会有任何额外的字符来扰乱您的下载。
对于那些感兴趣的人,我在下面粘贴了我的下载脚本。我的 zip 文件现在可以完美下载,到目前为止效果很好。
if (file_exists($zip_file_path)) {
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: public");
header("Content-Description: File Transfer");
//We can likely use the 'application/zip' type, but the octet-stream 'catch all' works just fine.
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename='$zip_file_name'");
header("Content-Transfer-Encoding: binary");
header("Content-Length: ".filesize($zip_file_path));
while (ob_get_level()) {
ob_end_clean();
}
@readfile($zip_file_path);
exit;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)