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 iOS绕地区网络检测
  • ¥15 python验证码滑块图像识别
  • ¥15 根据背景及设计要求撰写设计报告
  • ¥15 QT6颜色选择对话框显示不完整
  • ¥20 能提供一下思路或者代码吗
  • ¥15 用twincat控制!
  • ¥15 请问一下这个运行结果是怎么来的
  • ¥15 单通道放大电路的工作原理
  • ¥30 YOLO检测微调结果p为1
  • ¥15 DS18B20内部ADC模数转换器