public function download($id=null) { }
//You can find any field in the Attachment model, for instance if you want to find the Id just replace 'findByFilename' by 'findById'. The 'viewClass' will tell that a media will be downloaded. $attachment = $this->Attachment->findByFilename($id); $this->viewClass = 'Media'; //Here we specify parameters for the file that we will be going to download. The mimeType will determine what type of file the file to be downloaded is. You can find more file types by searching the net. $params = array( 'download' => false, 'id' => $attachment['Attachment']['filename'], 'name' => $attachment['Attachment']['filename'], 'download' => false, 'extension' => 'jpg', 'mimeType' => array( 'jpeg' => 'image/jpeg', 'jpg' => 'image/jpeg', 'png' => 'image/png', 'pdf' => 'application/pdf', 'doc' => 'application/msword', 'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'xls' => 'application/vnd.ms-excel', 'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ), 'path' => 'uploads'.DS ); //the last part is to invoke the parameter $this->set($params);That's it, you can now modify your Attachments.ctp table. Adding link to the filename you want to download by specifying the controller, action and also the parameter.
<table> <tr> <th>Filename</th><br /> </tr> <!-- Here is where we loop through our $posts array, printing out post info --> <?php foreach ($attachments as $attachment): ?> <tr> <td> <?php //This will trigger the download echo $this->Html->link($attachment['Attachment']['filename'], array('controller' => 'attachments', 'action' => 'download', $attachment['Attachment']['filename'])); ?> <?php //echo $document['Document']['control']; ?> </td> </tr> <?php endforeach; ?> <?php unset($attachment); ?> </table>
Labels: CakePHP 2.x, PHP, Scripts, Tutorial