Symfony 5 | Return an image via a controller route

Installation of the road

First of all you need a controller with a route ready to receive an image name, and then return the image.

Then you need to install the following package: compose require symfony/mime which will allow Symfony to automatically detect the mime type to return.

You also need to import these packages on top of the controller.

use Symfony\Component\HttpFoundation\BinaryFileResponse;
use Symfony\Component\HttpFoundation\JsonResponse;

My file tree

folders symfony 5

My image is in the uploads folder

Once the Controller and the route are ready, here is the code to enter to return an image under Symfony 5 :

    /**
     * @Route("/img-route/{img}", name="img_route")
     * A route with one parameter
     */
    public function index($img): Response
    {
        //Retrieve the root folder with the kernel and then add the location of the 
        //file
        $filename = $this->getParameter('kernel.project_dir') . '/uploads/' . $img;
        //If the file exists then we return it, otherwise return 404
        if (file_exists($filename)) {
            //return a new BinaryFileResponse with the file name
            return new BinaryFileResponse($filename);
        } else {
            return new JsonResponse(null, 404);
        }
    }

Result of the route

symfony 5 route return img

Here is the result by typing the route in your browser, it is possible to call this route with an api or a <img> tag to display the image.

This tutorial is now over, thanks for reading and feel free to share 🙂