src/Controller/DownloadController.php line 37

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  4. use Symfony\Component\Filesystem\Filesystem;
  5. use Symfony\Component\HttpFoundation\Response;
  6. class DownloadController extends AbstractController
  7. {
  8.     const TEMPORARY_FOLDER '/tmp';
  9.     /**
  10.      * @var Filesystem
  11.      */
  12.     private Filesystem $filesystem;
  13.     /**
  14.      * @param  Filesystem  $filesystem
  15.      */
  16.     public function __construct(Filesystem $filesystem)
  17.     {
  18.         $this->filesystem $filesystem;
  19.     }
  20.     /**
  21.      * @param  string  $name
  22.      * @param  string  $extension
  23.      * @return Response
  24.      */
  25.     public function downloadFileResult(string $namestring $extension 'csv'): Response
  26.     {
  27.         $temporaryFile sprintf('%s/%s'self::TEMPORARY_FOLDER$name);
  28.         $filename sprintf('%s.%s'$name$extension);
  29.         if (!$this->filesystem->exists($temporaryFile)) {
  30.             throw new \RuntimeException('Impossible to download this file.');
  31.         }
  32.         $response = new Response();
  33.         $response->headers->set('Content-Type''text/csv');
  34.         $response->headers->set('Content-Disposition'sprintf('attachment; filename=%s'$filename));
  35.         $response->setContent(file_get_contents($temporaryFile));
  36.         return $response;
  37.     }
  38. }