【问题标题】:how to download a .zip file after it has been compressed in php如何在 php 中压缩后下载 .zip 文件
【发布时间】:2016-05-10 10:05:37
【问题描述】:

我用函数压缩了一个文件夹,文件 (compressed.zip) 包含文件夹的所有内容。我对其进行了下载测试,一切正常。 现在我想在压缩完成后自动下载文件。

这是我使用的代码:

if(isset($_GET['compress'])) {
            // compress folder and sent compressed zip to plugins/sfm/views
            Zip($_GET['compress'], "plugins/sfm/views/compressed.zip");

            if(file_exists('plugins/sfm/views/compressed.zip')){
            // set example variables
            $filename = "compressed.zip";
            $filepath = "plugins/sfm/views/";

            // http headers for zip downloads
            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=\"".$filename."\"");
            header("Content-Transfer-Encoding: binary");
            header("Content-Length: ".filesize($filepath.$filename));
            ob_end_flush();
            @readfile($filepath.$filename);
            }


        }

就像我说的;当我通过 url 转到 plugins/sfm/views/compressed.zip 时,他毫无问题地提取了该文件夹,并且所有内容都在其中提取。 但是强制下载给了我一个似乎已损坏的压缩.zip。

当尝试使用 Winrar 打开下载时,他说:存档意外结束。并且:存档格式未知或已损坏。 为什么强制下载给我这个错误? zip文件压缩正确!

【问题讨论】:

  • 比较下载的文件和你强制下载的文件。
  • 我确认,文件已损坏。但是为什么强制下载会向浏览器传递损坏的文件?原文件完好无损
  • 我认为问题可能在空间或缓冲区缓存中 - 检查 stackoverflow.com/questions/13311790/… - 比较您的文件以检查差异。

标签: php download zip


【解决方案1】:

这似乎解决了问题:

//clean all levels of output buffering
while (ob_get_level()) {
ob_end_clean();
}

@readfile($filepath.$filename);之前

【讨论】:

  • 正是我的建议;)
猜你喜欢
  • 1970-01-01
  • 2011-05-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多