Yii使用Ajax上传文件 - 传递数据数组(formData)

时间:2014-12-01 16:30:53

标签: javascript php jquery ajax yii

我一直在抨击这一段时间,似乎一次推进小步骤。我需要为用户提供一种通过Ajax上传文件的方法。我已经看到需要使用formData来传递文件本身。使用这两个问题作为参考: Uploading file in Yii using ajax Yii ajax file upload

我的视图页面上有以下代码:

<?php
$form=$this->beginWidget('CActiveForm', array(
    'id'=>'post-form',

    'htmlOptions' => array('enctype' => 'multipart/form-data'),
    ));


echo '<div class="columns small-5">' . $form->fileField($upload, 'image') . '</div>';
echo $form->error($upload, 'image');
echo CHtml::button("(+)",array('title'=>"Topic",'onclick'=>'js:upload_file(this);')); 


$this->endWidget(); ?>

<script>
function upload_file(){
var fd = new FormData();
var e = document.getElementById("UploadedFiles_image");
fd.append( "UploadedFiles[image]", $(e)[0].files[0]);

$.ajax({
    url: 'UploadInstallPhoto',
    type: 'POST',
    cache: false,
    data: fd,
    datatype: 'json',
    processData: false,
    contentType: false,
    success: function (data) { 

    },
    error: function () {
        alert("ERROR in upload");
    }
});
}
</script>

我的控制器中包含以下代码:

    if(Yii::app()->request->isAjaxRequest)
    {

        $upload = new UploadedFiles;

        $upload->attributes = $_POST['UploadedFiles'];

        $file = CUploadedFile::getInstance($upload,'image');

        $pi = pathinfo($file);

        $upload->name = $pi['filename'];
        $upload->ext = $pi['extension'];
        $upload->acc_id = $id;
        $upload->type_id = 1;
        $upload->date_uploaded = date('Y-m-d');
        if($upload->save())
        {
            $file->saveAs(Yii::app()->params['uploadFiles'] . $upload->id . '.' . $pi['extension']);
            Yii::app()->user->setFlash('success',Yii::t('flash','flash.accounts.successful_upload'));
        }

    }

使用上面的代码,我现在可以执行ajax文件提交,这是按预期工作的。我现在面临的问题是文件被放入一个文件夹中,并创建了数据库中的一个条目。在DB中我引用了人员帐户,因此可以在该用户的帐户上看到该文件。

我需要做的是使用ajax POST传递一组数据,即

data: {file: fd, id: id}

但是,当我更改线条以使用数组时,不会发布任何数据。请有人建议可能的修复或如何传递多个值,包括文件值。

1 个答案:

答案 0 :(得分:1)

这是适合我的解决方案。我现在能够通过Ajax上传文件,并传递多个变量以及文件。

以下是查看页面的代码:

<?php
    $form=$this->beginWidget('CActiveForm', array(
        'id'=>'post-form',
        'htmlOptions' => array('enctype' => 'multipart/form-data'),
        ));


    echo '<div class="columns small-5">' . $form->fileField($upload, 'image') . '</div>';
    echo $form->error($upload, 'image');
    echo CHtml::button("(+)",array('title'=>"Topic",'onclick'=>'js:upload_file(this);')); 


    $this->endWidget();
?>

<script>
function upload_file(){
    var fd = new FormData();
    var e = document.getElementById("UploadedFiles_image");
    fd.append( "UploadedFiles[image]", $(e)[0].files[0]);
    fd.append( "UploadedFiles[acc_id]", <?php echo $model->account_id; ?>); //This lines appends the required ID, thanks to Adeneo

    $.ajax({
        url: 'UploadInstallPhoto',
        type: 'POST',
        cache: false,
        data: fd,
        datatype: 'json',
        processData: false,
        contentType: false,
        success: function(data){ 

        },
        error: function(){
            alert("ERROR in upload");
        }
    });
}
</script>

以下是我的控制器代码:

public function actionUploadInstallPhoto()
{
    if(Yii::app()->request->isAjaxRequest)
    {
        $upload = new UploadedFiles;

        $upload->attributes = $_POST['UploadedFiles'];

        $file = CUploadedFile::getInstance($upload,'image');

        $pi = pathinfo($file);

        $upload->name = $pi['filename'];
        $upload->ext = $pi['extension'];
        $upload->acc_id = $_POST['UploadedFiles']['acc_id'];
        $upload->type_id = Yii::app()->params['installPhoto'];
        $upload->date_uploaded = date('Y-m-d');
        if($upload->save())
        {
            $file->saveAs(Yii::app()->params['uploadFiles'] . $upload->id . '.' . $pi['extension']);
            Yii::app()->user->setFlash('success',Yii::t('flash','flash.accounts.successful_upload'));
        }

    }
}

希望这会帮助那些和我一样的人。