Zend Framework - 使用控制器返回图像/文件 [英] Zend Framework - Returning Image/File using Controller

查看:19
本文介绍了Zend Framework - 使用控制器返回图像/文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

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

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.

我通常在 ASP.NET MVC 中执行此操作,但不知道如何在此处执行此操作.如果有人能启发我如何实现它,我会很高兴.

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.

我设法找到了如何返回 JSON 并相信像这样简单的事情会起作用.但是找不到解决办法.我也需要发送这样的文件.

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.

提前致谢.

推荐答案

从 Zend Framework 2.0 到 2.1

如果你想返回一个图像,只需返回填充了内容的响应对象:这将告诉 Zend\Mvc\Application 完全跳过 Zend\Mvc\MvcEvent::EVENT_RENDER 事件并转到 Zend\Mvc\Application::EVENT_FINISH

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

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

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.

这篇关于Zend Framework - 使用控制器返回图像/文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆