Search code examples
file-iocakephp-2.1

How do Media Views work in cakephp?


I have arranged a file upload to happen on my application relative address: webroot/files

Now I need to force download on the uploaded files. After some googling and trying like most of the suggestions from this post I figured out the correct way to do this is using cakephps Media Views

What I have:

  1. Main site with a table of records. Model -> Record; Table -> records;
  2. These records have a primary key record_id.
  3. In my database I have a Table -> files; Model -> File;
  4. These files have a foreign key record_id and a field 'url' with the relative path to it's location.
  5. After creating a record with files, the files are correctly uploaded to the folder, which relative address is e.g. webroot/files/record_name/file and the tables in database are correctly updated.

What I want to do:

  1. After doubleclicking on one table row open a modal dialog with the information about the record. (done)
  2. In this modal dialog I want to display links that will force download on these files.

I tried many variations of this:

//the retrieving of data after debug looks fine//
$this->loadModel('File');
$files = $this->File->find('list', array(
    'conditions'=>array('File.record_id'=>$record_id),
    'fields' => array('File.Name', 'File.Url');
))

//actual display of url
foreach($files as $file_name => $file_url) {
    echo $this->Html->link($file_name, $file_url);
}

The resulting link looks exactly the way James Revillini presented

This is my actual question

Since that issue was not entirely solved, I thought it would be helpful not only for me, but for anybody who's searching for a quick solution for this problem to see a quick demonstration of how Media-views work. I have no idea where to move after making a dynamic download function:

    public function download($name, $path) {
    $this->viewClass = 'Media';
    $params = array(
        'id'        => $name,
        'name'      => $name,
        'download'  => true,
        'path'      => $path
        );
        $this->set($params);
    }

Solution

  • Point the link in the modal dialog for the resource to the download() function.

    Pass the Record.id to that function. In it find the file and auto-render it.

    It should work.