0
votes

I'm uploading an image file via AJAX ajaxFileUpload plugin which uses iframe to submit the file. I have successfully uploaded the file to my controller and I can see the tmp_name, name, error = 0 etc but when I use this $this->data['Card']['tmp_name'], with move_uploaded_file it always returns false regardless of the path being correct...I'm not sure from this point onwards.

Below is my code so far for view file...

function ajaxFileUpload() {
    $.ajaxFileUpload({
        url: '/cards/ajaxFrontCardUpload',
        secureuri: false,
        fileElementId: 'CardUploadFront',
        dataType: 'json',
        success: function (data, status) {
            console.log(data);
            $('#uploadFrontImage').attr('src', data.tmp_path);
        },
        error: function (data, status, e) {
            alert(e);
        }
    })
    return false;
}

$('#CardUploadFront').live('change', function () {
    ajaxFileUpload();
});

echo $form->file('Card.uploadFront', array('class'=>'file'));

Below is the controller function:

public function ajaxFrontCardUpload() {
        $this->layout = 'ajax';
        $tmp_name = $this->data['Card']['uploadFront']['tmp_name'];
        $tmp_name = $this->data['Card']['uploadFront']['tmp_name'].'/'.$this->data['Card']['uploadFront']['name'];
        $json_response['tmp_path'] = '/img/cards/temp/'.time().'.png';
        if(move_uploaded_file($tmp_name, $json_response['tmp_path'])){
            $json_response['response'] = 'true';
        }else{
            $json_response['response'] = 'false';
        }
        $this->set(compact('json_response'));
    }

Any ideas guys?

1

1 Answers

1
votes

The problem is in here:

public function ajaxFrontCardUpload() {
        $this->layout = 'ajax';
        $tmp_name = $this->data['Card']['uploadFront']['tmp_name'];
        $tmp_name = $this->data['Card']['uploadFront']['tmp_name'].'/'.$this->data['Card']['uploadFront']['name']; 
//notice here that $tmp_name now no longer references the path to the uploaded file
        $json_response['tmp_path'] = '/img/cards/temp/'.time().'.png';
        if(move_uploaded_file($tmp_name, $json_response['tmp_path'])){
            $json_response['response'] = 'true';
        }else{
            $json_response['response'] = 'false';
        }
        $this->set(compact('json_response'));
    }

The path to the uploaded file is stored in $this->data['Card']['uploadFrom']['tmp_name']. When you append '/'.$this->data['Card']['uploadFront']['name'] to it, your $tmp_name variable no longer points to the uploaded file. This is why move_uploaded_file is returning false.