Wednesday, August 10, 2011

A JQuery upload plugin with cakePHP

Those who had been developing for a while since the early days of Ajax would agree that building a progress bar for file uploads is not trivial.  Here I would like to introduce jQuery File Upload plugin

It has an example which actually works out-of-the-box.  But for integration, although not really cake-y, we actually need to create and modify some files here and there.

Note that there can be many different implementations. I start by creating a UploadComponent object. This is a modified version of the examples/upload.php file. I replace the __construct() function with initialize()

function initialize($controller, $settings = array(), $options=null ) {
$this->controller =& $controller;
...
In the controller that calls the UploadComponent, we have a upload() function that handles the logic. It is also part of the examples/upload.php file. The basic JQuery File Upload plugin has the ability to Add, View and Delete files, therefore we will need POST, GET, and DELETE request detection.

class MyController extends AppController {
$var components = array('Upload');

...

function upload() {
          $this->layout = 'json';
          Configure::write('debug', 0);
  
          switch ($_SERVER['REQUEST_METHOD']) {
              case 'HEAD':
              case 'GET':
                  $this->Upload->get();
                  break;
              case 'POST':
                  $this->Upload->post();
                  break;
              case 'DELETE':
                  $this->Upload->delete();
                  break;
              default:
                  header('HTTP/1.0 405 Method Not Allowed');
          }
}

The view code is the most straightforward part. It is the modified version of the example/index.html file. You can embed the code into any existing view you have. Some required jquery files are the jQuery v. 1.6+ for the prop function, jQuery UI v. 1.8+, and jQuery Templates plugin v. 1.0+ although in the JQuery File Upload page, it is listed as optional. If you do not include this file you will encounter the error $.tmpl is missing in your browser console. (If you have Firebug. But I assume you all do since people who read this most probably are developers anyway).

No comments: