我正在使用php ZipArchive动态创建一个zip文件并将其发送回用户.我暂时将压缩文件存储在文档根目录上的文件夹中,然后将其与代码一起发回
header('Content-type:application/zip');
header('Content-Disposition: inline; filename="'.("file.zip").'"');
header("Content-Transfer-Encoding: binary");
header("Content-Length:".filesize($file));
$fh = fopen($file,'rb');
fpassthru($fh);
Run Code Online (Sandbox Code Playgroud)
在第一次发布之后
$zip->close()
Run Code Online (Sandbox Code Playgroud)
确保文件未打开.我遇到的问题是 - 存储的zip文件是一个有效的存档,我可以在Windows 7,7Zip,WinZIP等中打开.但是,当我用上面的代码向下发送文件时,它最终会有一个0xD 0xA对在文件的开头,这足以使其损坏.我无法弄清楚这些角色可能来自哪里.这是fopen/fpassthru的已知错误吗?任何帮助将非常感激.
小智 14
我发现在删除header("Content-Length:".filesize($file));线路时修复了我同样的问题......
小智 6
经过多次尝试下载zip文件后,解决方案是:
$result = create_zip($files_to_zip,$fileZip,true,$path_parts['dirname']);
ob_clean();
ob_end_flush(); // more important function - (without - error corrupted
zip)
header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1
header('Content-Type: application/zip;\n');
header("Content-Transfer-Encoding: Binary");
header("Content-Disposition: attachment; filename=\"".basename($fileZip)."\"");
readfile($fileZip);
unlink($fileZip);
exit();
Run Code Online (Sandbox Code Playgroud)