使用ajax将文件发送到服务器

时间:2014-08-03 14:34:46

标签: php ajax yii

以下是我的观点:

<?php $modelupload=new Upload; ?>
<?php $form=$this->beginWidget('CActiveForm', array(
    'id'=>'upload-upload',
    'enableAjaxValidation'=>false,
    'htmlOptions'=>array(
        'onsubmit'=>"return false;",
        'enctype' => 'multipart/form-data',
    ),
)); ?>

<div class="row">
    <?php echo $form->labelEx($modelupload,'New name'); ?>
    <?php echo $form->textField($modelupload,'Name'); ?>
</div>


<div class="row">
    <?php echo $form->labelEx($modelupload,'File'); ?>
    <?php echo $form->fileField($modelupload,'Extra'); ?>
</div>

<div class="row">
    <?php echo $form->labelEx($modelupload,'Description'); ?>
    <?php echo $form->textArea($modelupload,'Description'); ?>
</div>

<?php echo CHtml::Button('Upload',array('onclick'=>'upload();')); ?>


<?php $this->endWidget(); ?>

<script type="text/javascript">

function upload(){
    var data=new FormData($("#upload-upload")[0]);
    var extra={data1:"some text i want to attach",data2:"more text"};
    data={data:data,extra:extra};
    $.ajax({
        type:"POST",
        url:'<?php echo Yii::app()->createAbsoluteUrl("site/upload"); ?>',
        data:{"command":data},
        dataType:"json",
        processData: false,
        contentType: false,
        success:function successFunc(arr){
             alert(arr['text']);
        },
        error:function errorFunc(){
             alert("Something went wrong.");
        }
    })
}

</script>

当我在服务器上检查$ _POST [&#39;命令&#39;]时,它表示它未设置且整个数组$ _POST为空...它没有文件上传工作正常,但是文件和multipart / form-data我不能让它工作......

如何从其他表单字段上传文件+附加信息+附上我自己的信息?我尝试了一些事情并阅读了其他人的问题,但我无法得到我想要的结果。

2 个答案:

答案 0 :(得分:0)

可能你可以解决这个问题..

 <?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'dimages-form',
 //'enableAjaxValidation'=>true,
 'enableClientValidation'=>true,
 'clientOptions'=>array(
 'validateOnSubmit'=>true,
 'afterValidate' => 'js:function(form, data, hasError) { 
                          if(hasError) {

                               alert("validation failed");

                            }
                            else 
                            {

                                  upload(form, data, hasError);
                                 //return true ;  for synchronize form submission not ajax
                            }
                    }',
                ),
 'htmlOptions'=>array('role'=>"form",'enctype' => 'multipart/form-data')));  
?>

将您想要的额外值作为隐藏字段....并且应该遵循此类表单的NAME组合

<input type="hidden" name="ModelName[hiddenFiels1]" id="ModelName_hiddenFiels1" value="desired data" />
<input type="hidden" name="ModelName[hiddenFiels2]" id="ModelName_hiddenFiels2" value="desired data"  />

传递您想要的隐藏字段...现在上传功能......

function upload(){
var data = new FormData(form[0]);
 $.ajax({

    "type":"POST",
    "url":form.attr('action'),
    "data": data,
    "async": false,
    "success":function(data){

           alert('success');

    },
    "cache": false,
    "contentType": false,
    "processData": false,
 });

}

可能更好的做法是做一个ajax调用可以帮助你解决你的问题......

并在服务器端...反向数据

if(isset($_POST['ModelName']))  or print_r($_POST);

并使用console ....或Simple REST Client来调试...

答案 1 :(得分:-1)

我编写了自己的XMLHttpRequest,而不是使用ajax,它工作正常!我可以使用

访问我在php中的数据
$arr=explode(',',$_POST['command']);

和我的文件

$file=CUploadedFile::getInstanceByName('File');

...我想这比使用ajax更好,但我仍然想知道如何使用ajax ...

function upload(){        
    var data=new FormData();
    var input=document.getElementById('Upload_Extra');
    var command=[$("#Upload_Name").val(),$("#Upload_Description").val(),"Some text I want to attach","more text"];
    data.append("command",command);
    data.append('File',input.files[0]);
    var xhr=new XMLHttpRequest();
    xhr.open('POST','<?php echo Yii::app()->createAbsoluteUrl("admin/upload");?>',true);
    xhr.onload=function(){
        if (this.status==200){
            var resp=JSON.parse(this.response);
            alert(resp.text);
        };
    };
    xhr.onerror=function(){
        alert("Something went wrong.");
    }
    xhr.send(data);
}