Symfony 5 | Return an image via a controller route

Web developer Front-End in Oise, France - Gary Deshayes <--Traduction

Created at : Wednesday 1 September 2021


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 :)

News publications :
Symfony

Created at : Monday 1 November 2021

Javascript Framework JS

Created at : Sunday 31 October 2021

Symfony

Created at : Wednesday 1 September 2021

Javascript Framework JS

Created at : Saturday 28 November 2020

Javascript SQL Framework JS

Created at : Sunday 20 September 2020

Symfony

Created at : Thursday 6 August 2020

Javascript jQuery

Created at : Monday 23 March 2020

Symfony

Created at : Friday 14 February 2020

Symfony Bugs

Created at : Sunday 26 January 2020