如何在yii2中显示public_html之外的图像?

时间:2016-07-07 15:38:10

标签: php yii yii2

我的问题是我尝试在项目的public_html文件夹之外显示一个图像,为此,在Yii中调用控制器方法的视图中,运行以下命令:

public function actionImagenreadfile2($file) {

    if(file_exists($file)){
        header('Content-Type: '. FileHelper::getMimeType($file));
        ob_clean();
        readfile($file);
    }
}

我从视图中调用此控制器的方式如下:

<img src="<?php Yii::$app->runAction('ficha/imagenreadfile2', ['file' => $imagen]); ?>">

其中$ imagen是图像路径,但是当显示图像显示为文本/计划时。

1 个答案:

答案 0 :(得分:2)

你应该修正你的观点:

<img src="<?= Url::to(['ficha/imagenreadfile2', 'file' => $imagen]); ?>">

您还可以在控制器中使用yii\web\Response::sendFile()

return \Yii::$app->response->sendFile($file);

详细了解sending file with Yii2

最重要的是,您应该检查$file,因为您的操作完全没有安全保护......