如果我的控制器没有尝试加载不存在的.ctp文件,我该如何渲染。
这是我的代码:
//without this, I get an error trying to load a non-existent .ctp file. When I include it, the browser does not render the PNG file.
$this->autoRender = false;
//... get avatar code
if (!file_exists($avatarPath))
throw new Exception('Could not find file: '.$avatarPath);
$file = file_get_contents($avatarPath);
header('Content-Type: image/png');
if ($file === false)
throw new Exception('file_get_contents failed on avatarPath');
else
echo $file;
当我使用$this->autoRender = false;
时,header
来电似乎会被忽略。有什么想法吗?
答案 0 :(得分:2)
使用CakePHP阅读how to send files。让我为您引用文档:
有时您希望将文件作为请求的响应发送。您可以使用
完成此操作
public function sendFile($id)
{
$file = $this->Attachments->getFile($id);
$this->response->file($file['path']);
// Return response object to prevent controller from trying to render
// a view.
return $this->response;
}
如上例所示,您必须将文件路径传递给方法。 CakePHP将发送一个正确的内容类型标题,如果它是Cake \ Network \ Reponse :: $ _ mimeTypes中列出的已知文件类型。您可以在使用Cake \ Network \ Response :: type()方法调用Cake \ Network \ Response :: file()之前添加新类型。
如果需要,您还可以通过指定选项强制下载文件而不是在浏览器中显示:
$this->response->file(
$file['path'],
['download' => true, 'name' => 'foo']
);