Yii的AJAX文件上传 [英] Yii ajax file upload

查看:363
本文介绍了Yii的AJAX文件上传的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要上传图片与Ajax调用。但是,POST场图像始终是空的。我的组成部分:

I need to upload image with ajax call. But POST field with image always is empty. Part of my form:

<div class="col-lg-6">
    <?php echo CHtml::activeFileField($model, 'logo'); ?>
    <?php echo CHtml::textField('test', 'test'); ?>
    <?php echo CHtml::submitButton('Upload'); ?>        
    <?php echo CHtml::ajaxSubmitButton('Upload ajax', '#');?>
</div>

如果我点击提交按钮,然后我有两个测试标志字段 - 图像上传。 如果我点击 ajaxSubmitButton ,那我也只能测试字段,标志是空的。有什么解决办法?

If i click submitButton, then i have both test and logo fields - image uploaded. And if i click ajaxSubmitButton, then i have only test field, logo is empty. What is the solution?

PS:我需要非扩展解决方案

PS: i need non-extension solution.

推荐答案

您无法在默认情况下上传与 ajaxSubmitButton 文件。使用简单提交或某些上传。 如果你想通过AJAX上传图片,这里的例子:

You cannot upload files with ajaxSubmitButton by default. Use simple submit or some uploader. If you want to upload image via ajax, here's example:

<?php echo CHtml::link('Upload ajax', '#', array("onclick"=>"js:upload_file(this)"));?>

在你的JS:

function upload_file(){
    var fd = new FormData();
    var e = document.getElementById("Model_logo");
    fd.append( "Model[logo]", $(e)[0].files[0]);
    $.ajax({
        url: 'upload',
        type: 'POST',
        cache: false,
        data: fd,
        processData: false,
        contentType: false,
        success: function (data) { 

        },
        error: function () {
            alert("ERROR in upload");
        }
    });
}

更改模型的型号名称和该会工作。另外现在您可以附加任何数据FORMDATA,它会在$ _ POST和$ _FILES文件传递。 要小心,这种方式不能在IE7和IE8工作,我记住了。

Change Model to your model name and this will work. Also now you can append any data to FormData and it will be passed in $_POST and your file in $_FILES. Be carefull, this way doesn't work on ie7 and ie8 as i remember.

这篇关于Yii的AJAX文件上传的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆