Ayoub
Ayoub

Reputation: 138

Return an image from a controller action in 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;
}

Upvotes: 4

Views: 4680

Answers (3)

Hackinet
Hackinet

Reputation: 3348

All the answers here are outdated.

I would suggest not using BinaryFileResponse or using file_get_contents since they would read the whole file and place it in your memory.

Please use StreamedResponse provided at Symfony\Component\HttpFoundation\StreamedResponse.

$imageFilePath = dirname(__FILE__)."/../../var/tmp/bean.jpg";
$streamedResponse = new StreamedResponse();
$streamedResponse->headers->set("Content-Type", 'image/png');
$streamedResponse->headers->set("Content-Length", filesize($imageFilePath));

$streamedResponse->setCallback(function() use ($imageFilePath) {
    readfile($imageFilePath);
});

return $streamedResponse;

Upvotes: 2

Matteo
Matteo

Reputation: 39470

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

Upvotes: 6

Niomin
Niomin

Reputation: 68

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.

Upvotes: 2

Related Questions