Zend Framework - Returning Image/File using Controller

匿名 (未验证) 提交于 2019-12-03 02:29:01

问题:

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.

回答1:

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.



回答2:

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; 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!