Komponent HttpFoundation udostępnia obiektowe mechanizmy, które obsługują specyfikację HTTP. Aby pobrać plik z serwera skorzystamy z dobrodziejstw tych klas:
1 2 3 4 |
use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\BinaryFileResponse; use Symfony\Component\HttpFoundation\ResponseHeaderBag; use Symfony\Component\HttpFoundation\File\Stream; |
Do tworzenia archiwum ZIP można wykorzystać klasę ZipArchive, o której pisałem w tym artykule: Tworzenie archiwum ZIP.
PRZYKŁAD
/src/Controller/ZipController.php:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
<?php namespace App\Controller; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Component\Routing\Annotation\Route; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\BinaryFileResponse; use Symfony\Component\HttpFoundation\ResponseHeaderBag; use Symfony\Component\HttpFoundation\File\Stream; use ZipArchive; class ZipController extends AbstractController { /** * @Route("/zip", name="zip") */ public function index(Request $request) { $archive = null; $dir = $this->getParameter('kernel.project_dir').'/public/images/'; if ($request->get('download') == 1) // if you click a hyperlink { // CREATE ARCHIVE $zip = new ZipArchive(); $archive = 'archive-'.uniqid().'.zip'; $zip->open($archive, ZipArchive::CREATE); $zip->addFile($dir.'example1.png'); $zip->addFile($dir.'example2.jpg'); $zip->close(); // DOWNLOAD ARCHIVE $file = new Stream($archive); $response = new BinaryFileResponse($file); $response->setContentDisposition(ResponseHeaderBag::DISPOSITION_ATTACHMENT, $archive); $response->deleteFileAfterSend(true); return $response; } return $this->render('zip/index.html.twig', ['archive' => $archive] ); } } |
/templates/zip/index.html.twig:
1 2 3 4 |
{% extends 'base.html.twig' %} {% block body %} <a href="{{ path('zip') }}?download=1">Create & Download ZIP Archive</a> {% endblock %} |
Przejdź do strony http://localhost/public/index.php/zip, a następnie kliknij hiperłącze, aby rozpocząć pobieranie pliku archiwum.
POBIERANIE PLIKU ZIP
Do obiektu strumienia (new Stream) przekazujemy archiwum:
1 |
$file = new Stream($archive); |
Z tego względu, że plik tworzony jest dynamicznie i jego rozmiar nie jest znany, strumień z plikiem archiwum przekazywany jest do obiektu klasy BinaryFileResponse:
1 |
$response = new BinaryFileResponse($file); |
Ustawiamy pole nagłówka odpowiedzi Content-Disposition na DISPOSITION_ATTACHMENT, czyli żądanie zapisu pliku do postaci załącznika:
1 |
$response->setContentDisposition(ResponseHeaderBag::DISPOSITION_ATTACHMENT, $archive); |
Na koniec usuwamy tymczasowy plik archiwum z serwera:
1 |
$response->deleteFileAfterSend(true); |
I to wszystko 🙂