yii2: how to response image and let browser show it?

后端 未结 5 2045
攒了一身酷
攒了一身酷 2021-01-05 02:37

the same work can be done by follow code:

header(\'Content-Type:image/jpeg\');
readfile(\'a.jpg\');

but now I really confused by Yii2\'s

5条回答
  •  北荒
    北荒 (楼主)
    2021-01-05 03:05

    in yii2 you can return a response object from class yii\web\Response in action. so you can return a own response.

    for example display image in 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;
    }
    

    FORMAT_RAW: the data will be treated as the response content without any conversion. No extra HTTP header will be added.

提交回复
热议问题