Here is a snippet how to send a file to download. It creates a zip archive and sends it.
<?php
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);
$archive->close();
return $response;
}
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);
$archive->close();
return $response;
}
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 😉
Hi, you need to implement getEntity. It is just a sample. You can also remove it and remplace $entity->getHash() by filename.
Cześć. Mam problem z archiwizacją. Stosuję Twoje rozwiązanie, ale przy pierwszym wywołaniu kontrolera, wyrzuca mi błąd
Warning:
file_get_contents(C:xampphtdocsmy_wwwreklamowacwebuploadsdocuments27.zip):
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ę.