jQuery Uploadify 2 + CodeIgniter

uploadify-logoCreating useful upload forms having become very popular on the web these days. Many people have found that flash based options create a more rich user experience. I was working on a project recently to allow a user to upload images to a CodeIgniter application. I enjoy using jQuery, and found an excellent flash based uploader in Uploadify. The most recent version added many new features over the previous version.  However, there seems to be a need for a quick tutorial for integrating Uploadify into CodeIgniter.  Here is a zip file that you can drop into your CodeIgniter application to see how it works.

Download CodeIgniter Uploadify Demo (updated 03/09/2011) (On right side, click click on get source)

The demo zip file contains the uploadify source files as well the controllers and views to get this to work. Just unzip the folder and drop into your CodeIgniter folder. The structure is:

  • /js/uploadify/ (uploadify files)
  • /system/application/controllers/upload.php
  • /system/application/views/upload/ (2 view files)
  • /uploads (blank folder where files are uploaded to)

The code is very simple and I have used it several different ways after getting this to work.  You will need to also add a standard upload form to the controller as well for users with Flash disabled. That’s part is pretty straight forward and is provide in the CodeIgniter user guide.  When I was first trying to integrate the two, I was trying too hard to find a solution using CI’s built in upload functions. I was reading in the documentation and found the onComplete callback.  I modified some of the code in the upload.php included in the uploadify source download. The file now echoes a JSON string back when the upload completes. The JSON string is then posted back to CodeIgniter using jQuery.

In /js/uploadify/uploadify.php where the upload is handled by the flash uploader, you will find the code creating the JSON string. You may add more values to the array where you would need them.

$filearray = array();
   $filearray['file_name'] = $newf_name;
   $filearray['real_name'] = $real_name;
   $filearray['file_ext'] = $file_ext;
   $filearray['file_size'] = $file_size;
   $filearray['file_path'] = $targetFile;
   $filearray['file_temp'] = $file_temp;
   $json_array = json_encode($filearray);
   echo $json_array;

Here is where the JSON string is handled in CodeIgniter

function uploadify()
		//Decode JSON returned by /js/uploadify/upload.php
		$file = $this->input->post('filearray');
		$data['json'] = json_decode($file);

An additional note pointed out in the CI forums is to be sure to add in your /application/config/mimes.php file for each file type you will be uploading: