Downloading Files in CakePHP


This is the continuation for Uploading Multiple Files in CakePHP. This lesson covers downloading of files being uploaded to your server. All we have to do is add the custom function below in your AttachmentsController.

public function download($id=null) {

}
The parameter will the function what file will be downloaded. Inside the function just add the script below. Just read the comments for to further understand it.

//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: , , ,