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...)
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.
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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With