A few words about media views (sending binary files to the user)

Media views is one really nice feature of CakePHP which doesn’t get much attention, so I figured to briefly cover it here. Actually the manual lists pretty much all you need to know about media views, but there are a couple of things that I’d like to point out. First, take a look at the brief example and more detailed explanation here: http://book.cakephp.org/view/489/Media-Views

One might ask what’s the point of using ‘id’ and ‘name’? Well, the ‘name’ key allows you to change the file name as it will be displayed to the user (in a “save” dialog, for example), it is not the actual name of the file on the server or at least it doesn’t have to be. For example, if you have a reporting tool that generates some files and their name on the server happens to be 329569364658875.zip, you can modify such ugly name on the fly by specifying: ‘name’ => ‘user_friendly_file_name’.

Also, remember that ‘path’ is relative to your app directory and requires a trailing DS (directory separator). Therefore if you have a path like /home/bob/cake/app/files_for_download, you specify:

And just to reiterate what the manual says, media views allow you to perform authentication before delivering content and you can deliver files which are not accessible from webroot to prevent direct linking.

P.S. Thanks to skiedr and Tarique Sani who’ve pointed out that you can now cache the files generated by media views, which ultimately means that images, etc. can be fetched from the browser cache if available.

Related Posts