Zend Framework - Returning an image / file using a controller

I am new to Zend Framework 2 and I know only a few reasons. It’s also hard for me to find many examples.

Quesiton: Get the BLOB field in the database and display it through the controller. For example: www.mysite.com/images/2 will extract the BLOB from the database and display it to the user as an image, therefore an html tag such as <img src="http://www.mysite.com/images/2"/> , displays the image.

I usually do this in ASP.NET MVC, but have no idea how to do it here. I would be glad if someone could enlighten me on how to achieve this.

Suppose I select an image from a database.

I managed to find how to return JSON and believe that such a simple thing would work. But could not find a solution. I will also need to send such files.

 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 have been obliged if someone could help.

Thanks in advance.

+2
source share
2 answers

Zend Framework 2.0 to 2.1

If you want to return the image, just return the response object filled with the contents: it will tell Zend\Mvc\Application completely skip the Zend\Mvc\MvcEvent::EVENT_RENDER 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 Zend\Mvc\Event::EVENT_FINISH , which in turn will be able to send a response to the output.

+11
source

In addition to Ocramius code, if you upload images to a folder inside the application, you can get the contents 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; 
0
source

All Articles