ZIParchive symfony2在Mac OS上返回zip损坏

时间:2016-04-07 21:51:21

标签: macos symfony nginx zip

我正在使用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;
}

问题出在Mac OS上,我在windows和linux OS上完美地提取了zip。但是在Mac OS中,我收到了一条错误消息" zip corrupted"。

1 个答案:

答案 0 :(得分:0)

它有效!只需添加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));