CakePHP-下载文件

CakePHP-下载文件,php,cakephp,download,cakephp-2.0,cakephp-2.1,Php,Cakephp,Download,Cakephp 2.0,Cakephp 2.1,我使用以下代码下载文件 public function sendFile($filePath,$filename) { $this->response->file($filePath, array('download' => true, 'name' => $filename)); return $this->response; } function download($id = null) { i

我使用以下代码下载文件

    public function sendFile($filePath,$filename) {             
    $this->response->file($filePath, array('download' => true, 'name' => $filename));
    return $this->response;
    }

function download($id = null) {
    if (!$id) {
        $this->Session->setFlash(__('Invalid id for upload', true));
        $this->redirect(array('action' => 'index'));
    }
    $upload = $this->Upload->findById($id);
    if (!$upload) {
        $this->Session->setFlash(__('Invalid id for upload', true));
        $this->redirect(array('action' => 'index'));
    }
    $filename = $upload['Upload']['filename'];
    $filePath = APP.'uploads'.DS.$id.DS;
    $this->sendFile($filePath,$filename);
}
但我得到了以下通知和错误

Notice (8): Undefined property: UploadsController::$response
Fatal error: Call to a member function file() on a non-object 

为了解决这个问题,我在谷歌上搜索了很多次,但都没用。

你们可以在控制器中使用下载方法


请参见链接

您的整个控制器是什么样子的?看起来这不是一个有效的真正的控制器。还要注意,你在那里做的事情是相当危险的。您不应该允许人们通过url在此处插入路径。这可能是一个巨大的安全漏洞!我已经编辑了包含真实控制器的代码,正如您所看到的,我没有从用户输入中获取路径。感谢您的建议。它不应该是控制器中的公共(因此可通过前端访问)方法。我的建议是要么使用组件,要么对其进行保护。您确定使用的是cakephp 2.x吗?在我看来更像是1.x代码。谢谢Mark,你说得对,我使用的是cakephp 1.x,我应该在编码之前阅读2.x书,还是你有一个在有限时间内学习使用cake编码的好参考资料?另外,不需要返回
return$this->response。您只需设置
$this->autoRender=false。从2.3版开始,MediaView已被弃用,您可以使用CakerResponse::file()将文件作为响应发送()