Search code examples
ajaxcakephppluginsuploader

CakePHP 2.1, Ajax & Miles Johnsons Uploader Plugin


I want to use the Plugin with CakePHP 2.1 as behaviour through $actAs = 'Uploader.Attachment'. While this works fine for static Uploads, I dont know how to use it for ajaxUploads.

The simple Question: Is there anyway to make an ajax-Upload happen through the actAs-Behaviour?

The explanation (if needed): The attachment Behaviour doesn't seem to have any defaults nor any other code regarding ajax (especially not the ajaxField in the following code). Though it works if I include the Plugin via

public function beforeFilter() {
    $this->Uploader = new Uploader(array(
        'ajaxField' => 'qqfile'
    ));
}

So I can use something like:

$data = $this->Uploader->upload($this->Uploader->ajaxField, array('overwrite' => true));

But not with:

$this->request->data;

This is not quite what I was seaching for, as I 1. Still need the actAs-Behaviour for other actions. 2. Have two different inclusions of the plugin, which I have to check that they do the same. 3. Can't automatically create thumbs and attach them to the same entry of the model.


Solution

  • This is what I did now for my specific case. Maybe it helps someone. Not beautiful but it works:

    public function beforeFilter() {
        $this->Uploader = new Uploader(array(
            'ajaxField' => 'qqfile'
        ));
    }
    
    public function ajax() {        
        $this->set('title_for_layout', 'Upload: AJAX File Upload');
        $this->render('ajax');
    }
    
    public function ajax_upload($album_id = null, $album_title = null) {
        $this->set('album_id', $album_id);
        $this->set('album_title', $album_title);
        $album_id = 2;
        $upload_dir = "uploads/$album_id/";
    
        $this->autoLayout = $this->autoRender = false;
        $this->Uploader->setup(array('uploadDir' => "$upload_dir"));
        $data = $this->Uploader->upload($this->Uploader->ajaxField, array(
            'overwrite' => true,
            'name' => 'uploaderFilename'
        ));
        //Creating a thumb
        $thumb_name = $data['custom_name']."_thumb.".$data['ext'];
        $this->Uploader->resize(array('width' => 250, 'expand' => true, 'aspect' => true, 'append' => '_thumb'));
        if (!empty($data)) {
            $this->Picture->set($data);   
            if ($this->Picture->validates()) {
                // Upload successful
                $data["album_id"]= $album_id;
                $data['path_thumb'] = $upload_dir.$thumb_name;
                $this->Picture->save($data);
                header('Content-Type: application/json');
                echo json_encode(array('success' => true, 'data' => $data));                                
            }
        }
    }