Zend Framework - Returning Image/File using Controller

 ̄綄美尐妖づ 提交于 2019-12-01 10:37:47

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.

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