Cakephp relative file path

In cakephp relative file paths are little tricky. Unless they are defined in the routes or in the actions/functions a file will not be rendered as you are expecting it to.   So many a times  or always you can use absolute paths to point to a file like an image or a video.

In  my scenario using the relative paths for a file was mandatory.  I was given a pre compiled swf file with relative paths encoded in it.  And the cakephp didn’t understand the filename in the url as it was.  So here is what I found in cakephp documentation which solved my problem of rendering the relative urls.

Media Views (From Cakephp site):

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' => APP . 'files' . DS
);
$this->set($params);
}
}

Hope you will find it useful too and will save your time.


2 Comments so far

hi!!i have a problem..when I downloadd the file (pdf),error message appears.in adobe reader “my file is corrup”

Did you check/open the file on you local machine? Also try to download the file from ftp and check to see if its working and not corrupt. The file may be corrupt by itself and the error might not be due to cakephp config.

Leave a comment

(required)

(required)




AUTHOR

profileWeb Developer working in advertising agency.

Recent tweets

The Twitter REST API v1 is no longer active. Please migrate to API v1.1. https://dev.twitter.com/docs/api/1.1/overview.