Zend Framework - 使用Controller返回图像/文件

Ziy*_*een 2 zend-framework2

我是Zend Framework 2的新手,只知道一些基础知识.我发现很难找到很多例子.

Quesiton:在数据库中获取BLOB字段并通过控制器显示它.例如:www.mysite.com/images/2将从数据库中检索BLOB并将其作为图像显示给用户,因此html标签<img src="http://www.mysite.com/images/2"/>将显示图像.

我通常在ASP.NET MVC中做,但不知道如何在这里做.如果有人能够告诉我如何实现它,我会很高兴.

假设我从数据库中获取了图像.

我设法找到了如何返回JSON并相信一些简单的东西会起作用.但找不到解决方案.我还需要发送这样的文件.

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
    }
}
Run Code Online (Sandbox Code Playgroud)

如果有人可以提供帮助,我将不得不承担责任.

提前致谢.

Ocr*_*ius 12

截至Zend Framework 2.0到2.1

如果你想返回一个图像,只需返回用内容填写的响应对象:这将告诉Zend\Mvc\Application完全跳过该Zend\Mvc\MvcEvent::EVENT_RENDER事件并转到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;
}
Run Code Online (Sandbox Code Playgroud)

这将导致应用程序短路Zend\Mvc\Event::EVENT_FINISH,这反过来又能够发送到输出响应的.