打开下载的zip文件将创建cpgz文件


Opening downloaded zip file creates cpgz file?

如果我将zip文件的url设置为链接的href并单击该链接,则会下载我的zip文件,打开它会获得我所期望的内容。

这是HTML:

<a href="http://mysite.com/uploads/my-archive.zip">download zip</a>

问题是,我希望链接指向我的应用程序,这样我就可以确定用户是否有权访问这个zip文件。

所以我希望我的HTML是这样的:

 <a href="/canDownload">download zip</a> 

和我的/canDownload页面的PHP:

//business logic to determine if user can download
if($yesCanDownload){
$archive='https://mysite.com/uploads/my-archive.zip';
header("Content-Type: application/zip");
header("Content-Disposition: attachment; filename=".basename($archive));
header("Content-Length: ".filesize($archive));
ob_clean();
flush();
echo readfile("$archive");
}   

所以,我认为问题与header()代码有关,但我已经根据各种谷歌和其他So建议尝试了很多与之相关的东西,但都不起作用。

如果你回答了我的问题,你很可能也能回答这个问题:用PHP压缩的文件在提取后会在cpgz文件中出现

在我的例子中,答案是在readfile()之前输出了一行空行。

所以我补充道:

ob_end_clean();

readfile($filename);

但是,您可能应该在代码中搜索输出此行的位置。

readfile的PHP文档说它将输出文件的内容并返回一个int。

因此,您的代码echo readfile("$archive");将返回$archive(顺便说一句,这里的双引号没有意义;您应该删除它们),然后输出返回的int。也就是说,您的线路应该是:readfile($archive);

此外,您应该使用存档的本地路径(而不是http://链接)。

总计:

if($yesCanDownload){
    $archive='/path/to/my-archive.zip';
    header("Content-Type: application/zip");
    header("Content-Disposition: attachment; filename=".basename($archive));
    header("Content-Length: ".filesize($archive));
    ob_clean();
    flush();
    readfile($archive);
}

最后,如果这不起作用,请确保filesize($archive)返回了文件的准确长度。

好的,我回答了我自己的问题。

我最初没有弄清楚的主要问题是,该文件不在我的应用程序服务器上。它在亚马逊AWS s3的一个桶里。这就是为什么我在问题中使用了完整的url http://mysite...,而不仅仅是服务器上的文件路径。事实证明,fopen()可以打开url(所有s3 bucket"对象",也就是文件,都有url),所以我就是这么做的。

这是我的最后一个代码:

$zip= "http://mysite.com/uploads/my-archive.zip"; // my Amazon AWS s3 url
header("Content-Type: archive/zip"); // works with "application/zip" too
header("Content-Disposition: attachment; filename='my-archive.zip"); // what you want to call the downloaded zip file, can be different from what is in the s3 bucket   
$zip = fopen($zip,"r"); // open the zip file
echo fpassthru($zip); // deliver the zip file
exit(); //non-essential

另一个可能的答案,我找到了。经过大量搜索,我发现*.zip"解压缩"到*.zip.cpgz的两个可能原因是:

  1. *.zip文件已损坏
  2. 正在使用的"解压缩"工具不能处理>2GB的文件

作为一名Mac用户,第二个原因是我解压缩文件时出现问题:标准的Mac操作系统工具是Archive Utility,它显然无法处理>2GB的文件。(对我来说,有问题的文件是一个压缩的4GB raspbian磁盘映像。)

我最终做的是使用一台Debian虚拟机,它已经存在于我的Mac上的virtual Box中。Debian 8.2上的unzip 6.0在解压缩归档文件时没有问题。

您将URL传递给readfile(),如:

$archive = 'https://mysite.com/uploads/my-archive.zip';

而您应该在服务器上传递路径,例如:

$archive = '/uploads/my-archive.zip';

假设文件位于上传文件夹中。

另外,请尝试以下标题:

header("Content-type: application/octet-stream"); 
header("Content-disposition: attachment; filename=file.zip");  

在我的案例中,我试图在public_html上方的目录中创建文件,但托管规则不允许。