开发者

Downloading files using media view in CakePHP

I want to download 4 different files through 4 different links. I am using the Media view to download the files, but I have to hardcode the file name in the download functions in the controller:

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

This works fine for one file. Now, for links number 2,3,4, do I need to create 3 different actions and give different file names in them, or is there a way in which I can use download() to only 开发者_StackOverflow中文版download the respective file depending on which link has been clicked?


That's what variables are for. Generic example:

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); 
} 


In CakePhp 2.x you will get error The view for YourController::download() was not found.

Use viewClass field in CakePHP 2.x:

$this->viewClass = 'Media';

See Media Views — CakePHP Cookbook v2.x documentation

UPD: Media Views are deprecated since CakePHP 2.3, and CakeResponse::file() should be used:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜