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

后端 未结 5 2044
攒了一身酷
攒了一身酷 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 02:58

    Yii2 already has built-in function for sending files. This way you do not need to set response format and content type will be detected automatically (you can override it if you wish):

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

    ..

    If the file is only temporary created for current download action you can use AFTER_SEND event to delete the file:

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

提交回复
热议问题