File downloading from a Symfony controller

Published on 2020-01-29 • Modified on 2020-01-29

In this snippet, we will see how to force the download of a file by the browser from a Symfony controller. As you can see, it's very easy thanks to the file() function which is part of the AbstractController. First, we must get the project root dir, here I use the getProjectDir() function of the kernel to build a file path, but we could also inject the kernel.project_dir parameter in our controller. Unlike the other runnable snippets, when hitting the "run" button below, you won't see the results of the snippet but the browser will propose you to download my (perfect! 😁) Makefile. You can also check its content in this snippet.

<?php declare(strict_types=1);

// src/Controller/Snippet/Snippet75Trait.php

namespace App\Controller\Snippet;

use Symfony\Component\HttpFoundation\BinaryFileResponse;
use Symfony\Component\HttpKernel\KernelInterface;

 * I am using a PHP trait to isolate each snippet in a file.
 * This code should be called from a Symfony controller extending AbstractController (as of Symfony 4.2)
 * or Symfony\Bundle\FrameworkBundle\Controller\Controller (Symfony <= 4.1).
 * Services are injected in the main controller constructor.
 * @property KernelInterface $kernel
trait Snippet75Trait
    public function snippet75(): BinaryFileResponse
        return $this->file($this->kernel->getProjectDir().'/Makefile'); // That's it! 😁

 Run this snippet  More on Stackoverflow   Read the doc  Random snippet