Yii2:如何更改/添加响应标头?

时间:2016-11-28 10:46:31

标签: php http web yii2

我和Yii2有一些关系。我尝试在控制器的操作中添加/设置响应头。以下是代码:

   Yii::$app->response->headers->set('Content-type', ['application/pdf']);
   Yii::$app->response->headers->set('Content-Disposition', ['inline', 'filename=' . $fileName]);
   Yii::$app->response->headers->set('Content-Transfer-Encoding', ['binary']);
   Yii::$app->response->headers->set('Content-Length', [$fileSize]);
   Yii::$app->response->headers->set('Accept-Ranges', ['bytes']);

   return readfile($filePath);

如果我将set()更改为add(),或者将数组中的第二个参数更改为string,那么就不会有任何反应。 Pdf文件未打开。但是,如果我使用本机PHP header()方法 - 一切正常。

2 个答案:

答案 0 :(得分:2)

Yii2超级简单的下载文件发送方式是

public function actionDownload()
{
    return \Yii::$app->response->sendFile('path/to/file.txt');
}

有关详细信息,请参阅the documentation

答案 1 :(得分:1)

方法set签名需要字符串作为值,因此最好用字符串替换数组,尽管它在非严格编码中没有任何区别。

无论如何 - 基于getDispositionHeaderValue Content-Disposition

'inline; filename=' . $fileName

最好使用Yii 2方法将文件发送到浏览器,如: