使用CakePHP中的媒体视图下载文件

时间:2011-02-05 06:54:45

标签: php cakephp

我想通过4个不同的链接下载4个不同的文件。我正在使用Media视图下载文件,但我必须在控制器的下载功能中对文件名进行硬编码:

function download () { 
    $this->view = 'Media'; 
    $params = array( 
          'id' => 'example.zip', 
          'name' => 'example', 
          'download' => true, 
          'extension' => 'zip', 
          'path' => APP . 'files' . DS 
   ); 
   $this->set($params); 
} 

这适用于一个文件。现在,对于2,3,4号链接,我是否需要创建3个不同的操作并在其中提供不同的文件名,或者是否有一种方法可以使用download()仅根据链接下载相应的文件已被点击?

2 个答案:

答案 0 :(得分:7)

这就是变量的用途。通用示例:

function download($fileId) {
    $file = // find the file you want to serve based on $fileId
    $pathInfo = pathinfo($file['path']);

    $this->view = 'Media'; 
    $params = array( 
          'id'        => $file['name'],
          'name'      => $pathInfo['filename'], 
          'extension' => $pathInfo['extension'], 
          'download'  => true, 
          'path'      => APP . 'files' . DS 
   ); 
   $this->set($params); 
} 

答案 1 :(得分:2)

在CakePhp 2.x中,您将收到错误The view for YourController::download() was not found.

在CakePHP 2.x中使用 viewClass 字段:

$this->viewClass = 'Media';

请参阅Media Views — CakePHP Cookbook v2.x documentation

UPD :自CakePHP 2.3以来,不推荐使用媒体视图,并且应使用CakeResponse::file()

$this->response->file($file['path'], array('download' => true, 'name' => 'foo'));
return $this->response;