douzou7012 2016-05-10 10:05
浏览 63
已采纳

如何在php中压缩后下载.zip文件

I compressed a folder with with a function and the file (compressed.zip) has all the content of the folder. I tested it to download and everything works fine. Now i want to automatically download the file after compression has done.

This is the code i use for that:

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);
            }


        }

Like i said; when i go to plugins/sfm/views/compressed.zip via the url he extracts the folder without problem and all the content is inside it with extraction. But the forced download gives me a compressed.zip that seems to be corrupted.

When trying to open the download with Winrar, he says: Unexpected end of archive. and: the archive is either in unknown format or damaged. Why the forced download gives me this error? The zip file is compressed correctly!

  • 写回答

1条回答 默认 最新

  • dongshuo6185 2016-05-10 10:57
    关注

    this seems to solve the problem:

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

    before the @readfile($filepath.$filename);

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效