Reputation: 3300
I am new to Zend Framework 2 and only know a little basics. I find it difficult to find a lot of examples as well.
Quesiton: Get BLOB field in database and display it through a controller. For example: www.mysite.com/images/2 will retrieve a BLOB from the database and display it to the user as an image so an html tag like <img src="http://www.mysite.com/images/2"/>
will display an image.
I normally do it in ASP.NET MVC but have no clue how to do it here. I would be delighted if some one could enlighten me on how to achieve it.
Assume that I have fetched the image from the database.
I managed to find how to return JSON and believe some thing simple like that would work. But couldn't find the solution. I will also need to send files like that.
public function displayAction()
{
$id = 10;
$albumImage = $this->getAlbumImageTable()->getAlbumImage($id);
if ($albumImages){
//Show the image $albumImage
//return JsonModel(array(...)) for json but for image ???
} else{
//Show some other image
}
}
I would be obliged if some one could help.
Thanks in advance.
Upvotes: 2
Views: 8301
Reputation: 1273
In addition to Ocramius' code, if you are uploading the images into a folder inside the application, you can retrieve the content, using:
$imageContent = file_get_contents('data/image/photos/default.png');
$response->setContent($imageContent);
$response
->getHeaders()
->addHeaderLine('Content-Transfer-Encoding', 'binary')
->addHeaderLine('Content-Type', 'image/png')
->addHeaderLine('Content-Length', mb_strlen($imageContent));
return $response;
Upvotes: 0
Reputation: 25431
As of Zend Framework 2.0 to 2.1
If you want to return an image, simply return the response object filled in with the content: that will tell the Zend\Mvc\Application
to entirely skip the Zend\Mvc\MvcEvent::EVENT_RENDER
event and go to Zend\Mvc\Application::EVENT_FINISH
public function displayAction()
{
// get image content
$response = $this->getResponse();
$response->setContent($imageContent);
$response
->getHeaders()
->addHeaderLine('Content-Transfer-Encoding', 'binary')
->addHeaderLine('Content-Type', 'image/png')
->addHeaderLine('Content-Length', mb_strlen($imageContent));
return $response;
}
This will cause the application to short-circuit to the Zend\Mvc\Event::EVENT_FINISH
, which in turn is capable of sending the response to the output.
Upvotes: 13