首页 文章

CakeResponse下载文件无效

提问于
浏览
0

我正在用cakePHP 2.x编写一个简单的应用程序 . 我需要允许用户上传和下载文件 . 上传工作正常,但我坚持下载动作 .

我有一个控制器名称Documents,包含下载操作:

public function download($id = null) {
    $this->Document->recursive = -1;
    $doc = $this->Document->find('first', array('conditions' => array('Document.id' => $id)));

    $filename = $doc['Document']['file_file_name'];

    $resp = new CakeResponse();
    $resp->download(Configure::read('upload_dir').'upload'.DS.$id.'_'.$filename);
    $resp->send();
}

是的我没有检查文件是否存在等等......但它只是用于测试 . 因此下载方法中的路径类似于:/ home / www-app / upload / $ id_ $ filename

当然,文件存在且两条路径相同 .

但我从chrome得到以下错误:

Erreur 6 (net::ERR_FILE_NOT_FOUND) : File or Directory not found

我尝试了$ resp-> file()方法,但cakePHP似乎不知道该方法 .

谢谢!

1 回答

  • 2

    你没有按照你应该的方式使用Cake2.x及其响应类(以及如何记录它!)

    不要使用新实例,已经有一个你需要使用的实例:

    $this->autoRender = false;
    $this->response->send();
    

    等等

    另外,使用autoRender false你不需要一个视图(如果你直接发送文件怎么办?) .

    Correction 2013-01-10: 你甚至不需要send() . autoRender部分本身应该足够了 . 然后,响应类将在调度过程结束时自动调用send():

    $this->autoRender = false;
    $this->response->file(Configure::read('upload_dir').'upload'.DS.$id.'_'.$filename);
    
    // optionally force download as $name
    $this->response->download($name);
    

相关问题