Cakephp 2.3.x发送文件并强制下载mp4文件

use*_*231 8 cakephp file download

我正在使用cakephp 2.3.1

我想强制下载一个mp4文件,每个http://book.cakephp.org/2.0/en/controllers/request-response.html#cake-response-file

在我的"视图"中,我有以下代码正确搜索文件名,找到文件名,并显示下载链接:

<?php $filename = APP . 'webroot/files/' . $dance['Dance']['id'] . '.mp4'; 
if (file_exists($filename)) {
    echo $this->Html->link('DOWNLOAD', array('controller' => 'dances', 'action' => 'sendFile', $dance['Dance']['id'])); 
    } else {
    echo 'Coming soon: available April 16th';
    }
?>
Run Code Online (Sandbox Code Playgroud)

当用户点击链接时,我想强制下载mp4文件.在我的控制器中,我有以下代码不起作用:

public function sendFile($id) {
    $file = $this->Attachment->getFile($id); //Note: I do not understand the 'Attachment' and the 'getFile($id)'
    $this->response->file($file['webroot/files/'], array('download' => true, 'name' => 'Dance'));
    //Return reponse object to prevent controller from trying to render a view
    return $this->response;
}   
Run Code Online (Sandbox Code Playgroud)

我不明白'附件'和'getFile()'

我收到以下错误:错误:在非对象上调用成员函数getFile()

我做错了什么,是否有其他文件我可以看到更好地理解这一点?

Thi*_*zzi 23

您不理解的行只是示例的一部分 - 它假定应用程序有一个调用的模型Attachment,并且它有一个名为的方法getFile.由于您没有Attachment模型(或者至少它对控制器不可见),因此您将获得"对非对象的成员函数调用"错误.但这并不重要:您需要担心的是提供完整的系统路径this->response->file().在您的示例中,您可以通过将该行更改为:

$this->response->file(WWW_ROOT.'files/'. $id .'.mp4', array('download' => true, 'name' => 'Dance'));
Run Code Online (Sandbox Code Playgroud)

你可以摆脱这$this->Attachment->getFile条线,因为它与你的情况无关.

如果有帮助,请告诉我!