Symfony2创建并下载zip文件

Bru*_*lho 14 php zip symfony

我有一个应用程序上传一些文件,然后我可以压缩为zip文件和下载.

出口行动:

public function exportAction() {
        $files = array();
        $em = $this->getDoctrine()->getManager();
        $doc = $em->getRepository('AdminDocumentBundle:Document')->findAll();
        foreach ($_POST as $p) {
            foreach ($doc as $d) {
                if ($d->getId() == $p) {
                    array_push($files, "../web/".$d->getWebPath());
                }
            }
        }
        $zip = new \ZipArchive();
        $zipName = 'Documents-'.time().".zip";
        $zip->open($zipName,  \ZipArchive::CREATE);
        foreach ($files as $f) {
            $zip->addFromString(basename($f),  file_get_contents($f)); 
        }

        $response = new Response();
    $response->setContent(readfile("../web/".$zipName));
    $response->headers->set('Content-Type', 'application/zip');
    $response->header('Content-disposition: attachment; filename=../web/"'.$zipName.'"');
    $response->header('Content-Length: ' . filesize("../web/" . $zipName));
    $response->readfile("../web/" . $zipName);
    return $response;
    }
Run Code Online (Sandbox Code Playgroud)

一切都好,直到行标题.每次我到这里我都会收到错误:"警告:readfile(../ web/Documents-1385648213.zip):无法打开流:没有这样的文件或目录"

怎么了?

为什么当我上传文件时,这些文件具有root权限,对于我创建的zip文件也是如此.

vin*_*ent 20

SYMFONY 3示例:

use Symfony\Component\HttpFoundation\Response;

/**
* Create and download some zip documents.
*
* @param array $documents
* @return Symfony\Component\HttpFoundation\Response
*/
public function zipDownloadDocumentsAction(array $documents)
{
    $files = [];
    $em = $this->getDoctrine()->getManager();

    foreach ($documents as $document) {
        array_push($files, '../web/' . $document->getWebPath());
    }

    // Create new Zip Archive.
    $zip = new \ZipArchive();

    // The name of the Zip documents.
    $zipName = 'Documents.zip';

    $zip->open($zipName,  \ZipArchive::CREATE);
    foreach ($files as $file) {
        $zip->addFromString(basename($file),  file_get_contents($file));
    }
    $zip->close();

    $response = new Response(file_get_contents($zipName));
    $response->headers->set('Content-Type', 'application/zip');
    $response->headers->set('Content-Disposition', 'attachment;filename="' . $zipName . '"');
    $response->headers->set('Content-length', filesize($zipName));

    @unlink($zipName);

    return $response;
}
Run Code Online (Sandbox Code Playgroud)


Bru*_*lho 9

解决了:

$zip->close();
header('Content-Type', 'application/zip');
header('Content-disposition: attachment; filename="' . $zipName . '"');
header('Content-Length: ' . filesize($zipName));
readfile($zipName);
Run Code Online (Sandbox Code Playgroud)

显然关闭文件很重要;)