在Cakephp中上传AJAX文件输入图像

时间:2011-12-12 15:51:08

标签: php jquery ajax cakephp

我正在通过AJAX ajaxFileUpload插件上传图片文件,该插件使用iframe提交文件。我已成功将文件上传到我的控制器,我可以看到tmp_name,name,error = 0等但是当我使用这个$ this-> data ['Card'] ['tmp_name']时,使用move_uploaded_file它总是返回false无论路径是否正确......从现在开始我都不确定。

以下是我目前为视图文件的代码...

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'));

以下是控制器功能:

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'));
    }

任何想法的人?

1 个答案:

答案 0 :(得分:1)

问题在于:

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'));
    }

上传文件的路径存储在$this->data['Card']['uploadFrom']['tmp_name']中。 当您向其'/'.$this->data['Card']['uploadFront']['name']追加$tmp_name时,您的move_uploaded_file变量不再指向上传的文件。这就是{{1}}返回false的原因。