CakePHP File Upload with AJAX & CakePHP upload plugin

I’m running CakePHP 2.6 with CakePHP Upload Plugin found here:

I’m trying to upload a base64 encoded image derived from Canvas with AJAX. I get the base64 encoded data just fine in my Cake controller. My problem is working in sync with the Upload plugin to save the image correctly. I want to pass the right data so the plugin can do it’s job as if I was submitting a normal cake form.

Currently I’m having a hard time figuring out if this is possible and if so how to prep the data in my controller so the beforeSave/afterSave methods of the plugin can do their work. This is what I’ve tried so far in my controller(shortened to highlight the parts in question).

Here I’m trying to prepare it as a file but the plugin doesn’t seem to kick in. Otherwise the plugin works fine when saving form data the cake way. Here is a direct link to the UploadBehavior file which I’m trying to work with:

Any help or tips in the right direction would be very appreciated. Thanks!

public function add() {

        if($this->RequestHandler->requestedWith('json')) {
            //Grab Json Data from Angular http request
            $jsonData = json_decode(utf8_encode(trim(file_get_contents('php://input'))), true);

            //Grab Canvas Image and base64 decode it
            $image_raw = $jsonData['canvas'];
            list($type, $image_raw) = explode(';', $image_raw);
            list(, $image_raw)      = explode(',', $image_raw);
            $image = base64_decode($image_raw);

            //Detect Image Mime Type
            $f = finfo_open();
            $mime_type = finfo_buffer($f, $image, FILEINFO_MIME_TYPE);
            $extension = substr($mime_type, strpos($mime_type, "/") + 1); 

            //Create Random File Name

            //Move the file to tmp folder
            file_put_contents('img/cache/'.$name, $image);

            //save tmp destination to tmp_name
            $tmp_name = 'img/cache/'.$name;

            //get file size of image
            $filesize = filesize($tmp_name);

            //Prep the file data
            $data['ProductImage']['0']['name'] = $name;
            $data['ProductImage']['0']['tmp_name'] = $tmp_name;
            $data['ProductImage']['0']['type'] = $mime_type;
            $data['ProductImage']['0']['size'] = $filesize;


Source: ajax

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.