Symfony2 create and download zip file

后端 未结 7 823
Happy的楠姐
Happy的楠姐 2020-12-15 06:51

I have one application that upload some files and then I can compress as zip file and download.

The export action:

public function exportAction() {
          


        
7条回答
  •  长情又很酷
    2020-12-15 07:06

    SYMFONY 3 - 4 example :

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

提交回复
热议问题