【问题标题】:Zend Framework - Returning Image/File using ControllerZend 框架 - 使用控制器返回图像/文件
【发布时间】:2013-02-11 10:56:45
【问题描述】:

我是 Zend Framework 2 的新手,只知道一点基础知识。我也很难找到很多例子。

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

我通常在 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
    }
}

如果有人可以提供帮助,我将不胜感激。

提前致谢。

【问题讨论】:

    标签: zend-framework2


    【解决方案1】:

    从 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;
    }
    

    这将导致应用程序将short-circuit 发送到Zend\Mvc\Event::EVENT_FINISH,而Zend\Mvc\Event::EVENT_FINISH 又能够将响应发送到输出。

    【讨论】:

    • 那真是太好了,mb_strlen 有问题,我删除了它:D。
    • 这是一个非常消耗CPU的动作,你知道有什么解决办法吗?
    • 对我来说mb_strlen 不起作用,需要strlen。如果你没有得到完整的图像,或者错误的响应,你可以试试这个。完全去除整体也可以像紫妍建议的那样工作。
    【解决方案2】:

    除了 Ocramius 的代码,如果您将图像上传到应用程序内的文件夹中,您可以使用以下方法检索内容:

    $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;
    

    【讨论】:

      猜你喜欢
      • 2012-04-22
      • 2013-09-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多