如何下载文件cakephp 2.4

时间:2014-03-07 12:42:20

标签: cakephp

我有4种不同类型的文件可供下载image / doc / pdf / xls。我点击文件链接后想下载文件。

//控制器

public function sendFile($id) {
    $file = $this->Attachment->getFile($id);
    $this->response->file($file['path']);
    // Return response object to prevent controller from trying to render
    // a view
    return $this->response;
}

//视图

<a href="<?php echo $this->response->file($file->path); ?>"><?php echo $file->name; ?></a>

2 个答案:

答案 0 :(得分:2)

无需返回回复 - 请参阅this。 只需使用

public function send_file($id = null) {
    ...
    $this->autoRender = false;
    $this->response->file($file['path']);
}

在您的视图中,您需要链接到此控制器操作(如果您考虑的话):

$this->Html->link('Download', array(
    'controller' => 'controller_name', 'action' => 'send_file', $id
));

另请注意我为您更正的惯例 - 文档也告诉您。

答案 1 :(得分:0)

只是为了完成并添加关于Mark答案的一些注释

只需使用

public function send_file($file_name = null) {
    //local machine to the file
    //e.g. c:\wamp\www\project\...
    $path_local = 'path to the file'.$file_name;

    //live path to the file
    //e.g. \var\...
    $path_live = 'path to the file'.$file_name;

    $this->autoRender = false;
    //if you trying to test it from localhost set the localhost path 
    //other wise live path
    $this->response->file($path_live or $path_local, array('download' => true));
}

在您的视图中,您需要链接到此控制器操作(如果您考虑的话):

$this->Html->link('Download', array(
    'controller' => 'controller_name', 'action' => 'send_file', $file_name
));

另请注意我为您更正的惯例 - 文档也告诉您。

相关问题