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

后端 未结 5 2048
攒了一身酷
攒了一身酷 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:10

    I do it like this. I have added another function just for setting the headers. You can move this function in a helper too:

    $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");
    }
    

    I also found how yii2 does it, take a look here (scroll to the bottom) https://github.com/yiisoft/yii2/blob/48ec791e4aca792435ef1fdce80ee7f6ef365c5c/framework/captcha/CaptchaAction.php

提交回复
热议问题