3.9.5 Media Views

Media views allow you to send binary files to the user. For example, you may wish to have a directory of files outside of the webroot to prevent users from direct linking them. You can use the Media view to pull the file from a special folder within /app/, allowing you to perform authentication before delivering the file to the user.

To use the Media view, you need to tell your controller to use the MediaView class instead of the default View class. After that, just pass in additional parameters to specify where your file is located.

class ExampleController extends AppController {
    function download () {
        $this->view = 'Media';
        $params = array(
              'id' => 'example.zip',
              'name' => 'example',
              'download' => true,
              'extension' => 'zip',
              'path' => 'files' . DS
       );
       $this->set($params);
    }
}
  1. class ExampleController extends AppController {
  2. function download () {
  3. $this->view = 'Media';
  4. $params = array(
  5. 'id' => 'example.zip',
  6. 'name' => 'example',
  7. 'download' => true,
  8. 'extension' => 'zip',
  9. 'path' => 'files' . DS
  10. );
  11. $this->set($params);
  12. }
  13. }
ParametersDescription
idThe ID is the file name as it resides on the file server including the file extension.
nameThe name allows you to specify an alternate file name to be sent to the user. Specify the name without the file extension.
downloadA boolean value indicating whether headers should be set to force download.
extensionThe file extension. This is matched against an internal list of acceptable mime types. If the mime type specified is not in the list, the file will not be downloaded.
pathThe folder name, including the final directory separator. The path is relative to the APP folder.