Symfony 2: Sending a file to download from controller

Here is a snippet how to send a file to download. It creates a zip archive and sends it.


namespace Acme\DemoBundle\Controller;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\ResponseHeaderBag;
use ZipArchive;

class MyController extends Controller
     * @Route("/", name="index")

    public function indexAction()
        $entity = $this->getEntity();

        $index = $this->renderView('Acme:Demo:index.html.twig');
        $archive = new ZipArchive();
        $archive->open($this->get('kernel')->getRootDir() . '/../web/zip/' . $entity->getHash() . '.zip', ZipArchive::CREATE);
        $archive->addFromString($entity->getHash() . '.php', $index);  
        $response = new Response(file_get_contents($archive->filename));
        $d = $response->headers->makeDisposition(ResponseHeaderBag::DISPOSITION_ATTACHMENT, $entity->getHash() . '.zip');
        $response->headers->set('Content-Disposition', $d);
        return $response;


HttpFoundation Component documentation: Downloading Files

Join the Conversation


  1. I wan’t to try this example but the error is the method getEntity() is undefined ? How I can solve this problem and thank in advance ­čśë

  2. Hi, you need to implement getEntity. It is just a sample. You can also remove it and remplace $entity->getHash() by filename.

  3. Cze┼Ť─ç. Mam problem z archiwizacj─ů. Stosuj─Ö Twoje rozwi─ůzanie, ale przy pierwszym wywo┼éaniu kontrolera, wyrzuca mi b┼é─ůd

    failed to open stream: No such file or directory

    podczas gdy taki plik został utworzony. Jeżeli drugi raz wywołam kontroler, to ZIP jest pobierany.

    Czy m├│g┼éby co┼Ť doradzi─ç.

    Z g├│ry dzi─Ökuj─Ö.

Leave a comment

Your email address will not be published. Required fields are marked *