ZIParchive symfony2 返回 zip 在 Mac OS 上损坏

ZIParchive symfony2 returning zip corrupted on Mac OS

我正在使用 symfony 2.0,我正在尝试动态生成一个 zip。

这是我的代码:

public function singleZipAction(Request $request,$id){

    $user = $this->container->get('security.context')->getToken()->getUser();
    $images_root = $request->getScheme() . '://' . $request->getHttpHost() . $request->getBasePath().'/uploads/gallery/';

    $zip = new \ZipArchive();
    $fs = new Filesystem();

    try {
        $fs->mkdir('archives/'.date("d-m-Y").'/'.$user->getApikey().'/');
        $fs->chmod('src', 0700, 0000, true);
    } catch (IOExceptionInterface $e) {
        echo "An error occurred while creating your directory at ".$e->getPath();
    }

    $zipName =  'archives/'.date("d-m-Y").'/'.$user->getApikey().'/commande_'.$commande->getId().".zip";
    $name = 'commande_'.$commande->getId().'.zip';
    if($zip->open($zipName,\ZipArchive::CREATE | \ZipArchive::OVERWRITE) === TRUE){
        foreach ($new_array as $f) {
            $path = $images_root.$f->getFilePath();
            $file = 'uploads/gallery/'.$f->getFilePath();
            $zip->addFile($file,basename($file));
        }
        $zip->close();
    }else {
        die("can not open");
    }

    $response = new Response();
    $response->headers->set('Content-type', 'archive/zip');
    $response->headers->set('Content-Disposition', 'attachment; filename="' . $name . '";');
    $response->sendHeaders();
    $response->setContent(file_get_contents($zipName));
    return $response;
}

问题出在MacOS,我完美解压了windows和linuxOS上的zip。但在 Mac OS 中,我收到一条错误消息 "zip corrupted"。

有效!只需添加 ob_end_clean();在 setContent

之前

while (ob_get_level()) { ob_end_clean(); }

    $response = new Response();
    // Set headers
    $response->headers->set('Pragma', 'public');
    $response->headers->set('Expires', '0');
    $response->headers->set('Cache-Control', 'must-revalidate, post-check=0, pre-check=0');
    $response->headers->set('Cache-Control', 'public');
    $response->headers->set('Content-Description', 'File Transfer');
    $response->headers->set('Content-type', 'application/octet-stream');
    $response->headers->set('Content-Disposition', 'attachment; filename="' . $name . '";');
    $response->headers->set('Content-Transfer-Encoding', 'binary');
    $response->headers->set('Content-length', filesize($name));
    // Send headers before outputting anything
    //$response->sendHeaders();
    while (ob_get_level()) {
        ob_end_clean();
    }  
    $response->setContent(file_get_contents($zipName));