Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

yii2

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 \yii\web\Response.


What I confused is like that:

  1. create a controller and action to provide picture

    See below

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

thanks for the answer!

like image 757
haoliang Avatar asked Jan 06 '15 13:01

haoliang


Video Answer


1 Answers

Finally, I did it by follow codes:

$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();
like image 83
haoliang Avatar answered Oct 20 '22 12:10

haoliang