8

我正在使用 cakephp 2.3.1

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

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

<?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';
    }
?>

当用户单击链接时,我想强制下载 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;
}   

我不明白“附件”和“getFile()”

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

我做错了什么,是否有任何其他文档可以让我更好地理解这一点?

4

2 回答 2

23

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

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

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

让我知道这是否有帮助!

于 2013-03-04T21:58:55.840 回答
1
public function downloadfile($id= null) {        
  $this->response->file(APP.'webroot\files\syllabus'.DS.$id,array('download'=> true, 'name'=>'Syllubus'));
  return $this->response;     
}

<?php echo $this->Html->link('Syllabus', 
  array('controller' => 'coursesubjects',
    'action'=>'downloadfile',
    $courseSubject['CourseSubject']['subject_syllabus']));
?>
于 2013-05-07T11:50:08.800 回答