Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return an image from a controller action in symfony

Tags:

symfony

I need to access an image by providing its name in the url path, i tried to use this code but the image is not showing

  /**
 *
 * @Route("images/{imgname}",name="workflow_image")
 */
public function WorkflowImageAction(Request $request,$imgname){



    $filepath = $this->get('kernel')->getRootDir().'/../web/images/workflow/'.$imgname;

    $file =    readfile($filepath);

    $headers = array(
        'Content-Type'     => 'image/png',
        'Content-Disposition' => 'inline; filename="'.$file.'"');
    return $file;
}
like image 576
Ayoub Avatar asked Mar 13 '23 13:03

Ayoub


2 Answers

if you are serving a static file, you can use a BinaryFileResponse:

use Symfony\Component\HttpFoundation\BinaryFileResponse;

$file = 'path/to/file.txt';
$response = new BinaryFileResponse($file);

return $response;

More info about Serving Files in Symfony2 in the doc.

Hope this help

like image 115
Matteo Avatar answered Mar 15 '23 04:03

Matteo


Are you sure, it's a good idea to share image through php?

You can write some rules for folder web/image/workflow in your server (nginx or apache).

Share them through php is bad idea. Nginx/apache can do it very fast, not using RAM (php read full image in RAM). Also, nginx/apache can cache this image.

like image 20
Niomin Avatar answered Mar 15 '23 02:03

Niomin