yii2:如何响应图片并让浏览器显示出来?

hao*_*ang 6 yii2

可以通过以下代码完成相同的工作:

header('Content-Type:image/jpeg');
readfile('a.jpg');
Run Code Online (Sandbox Code Playgroud)

但是现在我对Yii2感到很困惑 \yii\web\Response.


我困惑的是这样的:

  1. 创建一个控制器和动作来提供图片

    见下文

    class ServerController extends \yii\web\Controller
    {
        public function actionIndex($name)
        {
            // how to response
        }
    }
    
    Run Code Online (Sandbox Code Playgroud)
  2. 访问 http://example.com/index.php?r=server/index&name=foo.jpg

谢谢你的回答!

hao*_*ang 16

最后,我按照以下代码做到了:

$response = Yii::$app->getResponse();
$response->headers->set('Content-Type', 'image/jpeg');
$response->format = Response::FORMAT_RAW;
if ( !is_resource($response->stream = fopen($imgFullPath, 'r')) ) {
   throw new \yii\web\ServerErrorHttpException('file access failed: permission deny');
}
return $response->send();
Run Code Online (Sandbox Code Playgroud)


Thi*_*Big 5

在yii2中,您可以从类yii\web\Response中返回响应对象.所以你可以回复自己的回复.

例如,在yii2中显示图像:

public function actionIndex() {
    \Yii::$app->response->format = yii\web\Response::FORMAT_RAW;
    \Yii::$app->response->headers->add('content-type','image/png');
    \Yii::$app->response->data = file_get_contents('file.png');
    return \Yii::$app->response;
}
Run Code Online (Sandbox Code Playgroud)

FORMAT_RAW:数据将被视为响应内容,无需任何转换.不会添加额外的HTTP标头.


Igo*_*mić 5

Yii2已经具有内置的发送文件功能。这样,您无需设置响应格式,并且内容类型将被自动检测到(如果需要,可以覆盖它):

function actionDownload()
{
    $imgFullPath = 'picture.jpg';
    return Yii::$app->response->sendFile($imgFullPath);
}
Run Code Online (Sandbox Code Playgroud)

..

如果仅是为当前下载操作临时创建的文件,则可以使用AFTER_SENDevent删除文件:

function actionDownload()
{
    $imgFullPath = 'picture.jpg';
    return Yii::$app->response
        ->sendFile($imgFullPath)
        ->on(\yii\web\Response::EVENT_AFTER_SEND, function($event) {
            unlink($event->data);
        }, $imgFullPath);
}
Run Code Online (Sandbox Code Playgroud)


Mih*_* P. 4

我就是这样做的。我添加了另一个函数只是为了设置标题。您也可以在助手中移动此函数:

$this->setHttpHeaders('csv', 'filename', 'text/plain');

/**
 * Sets the HTTP headers needed by file download action.
 */
protected function setHttpHeaders($type, $name, $mime, $encoding = 'utf-8')
{
    Yii::$app->response->format = Response::FORMAT_RAW;
    if (strstr($_SERVER["HTTP_USER_AGENT"], "MSIE") == false) {
        header("Cache-Control: no-cache");
        header("Pragma: no-cache");
    } else {
        header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
        header("Pragma: public");
    }
    header("Expires: Sat, 26 Jul 1979 05:00:00 GMT");
    header("Content-Encoding: {$encoding}");
    header("Content-Type: {$mime}; charset={$encoding}");
    header("Content-Disposition: attachment; filename={$name}.{$type}");
    header("Cache-Control: max-age=0");
}
Run Code Online (Sandbox Code Playgroud)

我还发现了 yii2 是如何做到的,请看这里(滚动到底部)https://github.com/yiisoft/yii2/blob/48ec791e4aca792435ef1fdce80ee7f6ef365c5c/framework/captcha/CaptchaAction.php