September 24, 2014

September 24, 2014
In this article, we are going to discuss about How to add file download option in CakePHP. CakePHP is an open source web application framework. It follows the Model-View-Controller (MVC) approach and is written in PHP, modeled after the concepts of Ruby on Rails, and distributed under the MIT License. CakePHP uses well-known software engineering concepts and software design patterns, as Convention over configuration, Model-View-Controller, Active Record, Association Data Mapping, and Front Controller.

To add the file download option in CakePHP, include the below action in your controller, from which controller you want to execute the download

function file_download($file_name = null) {
        $this->autoRender = false;
        $this->set('fileName', $file_name);
        
            header('Content-Type: application/download');
            $url = WWW_ROOT.DS.'fileFolderName'.DS.$file_name;
            
            header("Content-Disposition: attachment; filename=".basename($url));
            header("Content-Length: " . filesize($url));

            $fp = fopen($url, "r");
            fpassthru($fp);
            fclose($fp);
}

Now add the following link in your View file from where you want to download the file

echo $this->Html->link(__('Download', true), array('controller' => 'mycontroller','action' => 'pdf_download', $file['file_name']));
/* Here $file['file_name'] is the name of your file. */

0 comments:

Post a Comment