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
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();
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);
}
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.
The Yii2 way:
Yii::$app->response->setDownloadHeaders($filename);
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