Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return Image from Controller symfony2

I would like to know how can i return an image from the controller without any template. I would like to use it for pixel tracking in a newsletter.

I start with this code

    $image = "1px.png";
    $file =    readfile("/path/to/my/image/1px.png");
    $headers = array(
        'Content-Type'     => 'image/png',
        'Content-Disposition' => 'inline; filename="'.$file.'"');
    return new Response($image, 200, $headers);

But on the navigator i have a broken link (file not found...)

like image 756
Arnaud B Avatar asked Jul 01 '13 16:07

Arnaud B


3 Answers

According to the Symfony Docs when serving files you could use a BinaryFileResponse:

use Symfony\Component\HttpFoundation\BinaryFileResponse;
$file = 'path/to/file.txt';
$response = new BinaryFileResponse($file);
// you can modify headers here, before returning
return $response;

This BinaryFileResponse automatically handles some HTTP request headers and spares you from using readfile() or other file functions.

like image 86
franbenz Avatar answered Sep 22 '22 09:09

franbenz


Right now you return the filename as response body and write the file-content to the filename property of Content-Disposition.

return new Response($image, 200, $headers);

should be:

return new Response($file, 200, $headers);

... and ...

'Content-Disposition' => 'inline; filename="'.$file.'"');

should be ...

'Content-Disposition' => 'inline; filename="'.$image.'"');

right?

Further take a look at this question.

like image 29
Nicolai Fröhlich Avatar answered Sep 20 '22 09:09

Nicolai Fröhlich


This works fine for me.

$filepath = "/path/to/my/image/chart.png";
$filename = "chart.png";

$response = new Response();
$disposition = $response->headers->makeDisposition(ResponseHeaderBag::DISPOSITION_INLINE, $filename);
$response->headers->set('Content-Disposition', $disposition);
$response->headers->set('Content-Type', 'image/png');
$response->setContent(file_get_contents($filepath));

return $response;
like image 27
Francesco Avatar answered Sep 21 '22 09:09

Francesco