yii2上传ajax文件

2022-01-07 00:00:00 php ajax yii2

我想在 yii2 框架中使用 Ajax 上传文件这是我的代码,但在控制器get Instance"中由于序列化数据而返回 null;我该怎么做?

这是我的控制器:

$id,]);if ($model->load(Yii::$app->request->post())) {$model->file = UploadedFile::getInstance($model, 'file');$model->file->saveAs('uploads/signature/'.$model->user_id.'.'.$model->file->extension);$model->url = '上传/签名/' .$model->user_id .'.'.$model->file->extension;如果 ($model->save()) {回声 1;} 别的 {回声 0;echo $model->file;}} 别的 {return $this->renderAjax('update', ['模型' =>$模型,]);}}?>

这是我的脚本代码我无法在控制器中获取我的文件,它返回 null

<?php $script = <<<JS$('form#{$model->formName()}').on('beforeSubmit', function(e){var $form = $(this);$.post($form.attr("动作"),$form.serialize(),).完成(功能(结果){如果(结果 == 1){$(document).find('#update_signature_modal').modal('hide');$.pjax.reload({container:'#branchesGrid'});//警报();} 别的 {警报(结果);}}). 失败(函数(){console.log("服务器错误");});返回假;});JS;$this->registerJs($script);?>

解决方案

请先参考这里

问题

ajax 的问题是 $_FILES 详细信息没有在异步请求中发送.当我们在没有ajax请求的情况下提交填写好的表单并在PHP后端调试

echo '

';打印_r($_FILES);打印_r($_POST);echo '</pre>';死;

然后我们成功地获得了 $_FILES$_POST 数据.

但是当我们在 ajax 请求中调试同样的东西时,我们只得到 $_POST 值,我们得到 $_FILES 作为 NULL.这使我们得出结论,$_FILES 数据不是通过我们的上述代码在 ajax 请求中发送的.

解决方案

我们需要使用FormData的 JavaScript.

它有什么作用?

简单来说就是把需要上传的文件的所有必要信息添加到$.ajax中的data参数中或者填写$_FILES 以及所有 $_POST 数据,即非文件输入,例如字符串数字等.

在您的视图文件中

 ['enctype' => 'multipart/form-data']]) ?><?= $form->field($model, 'title') ?><?= $form->field($model, 'imageFile')->fileInput() ?><button type="button" class="btn btn-success subm">上传</button><?php ActiveForm::end();?><脚本>$('.subm').click(function(e){var formData = new FormData($('form')[0]);控制台日志(表单数据);$.ajax({url: "some_php_file.php",//处理数据的服务器脚本类型:'POST',//表单数据数据:表单数据,beforeSend: beforeSendHandler,//它是一个你必须定义的函数成功:功能(响应){控制台日志(响应);},错误:函数(){alert('PHP 端出错!!');},//告诉jQuery不要处理数据或担心内容类型的选项.缓存:假,内容类型:假,过程数据:假});});

测试

现在通过 print_r() 在 PHP 代码中发出 ajax 请求和调试,如上所示,您会注意到 $_FILES 不是 NULL 并且它包含所有文件(其中需要上传)数据.如果设置了,您可以使用 move_uploaded_file() 功能

上传

这就是您通过 Ajax 上传文件的方式.

参考 1

参考 2

参考 3

I want to upload file using Ajax in yii2 framework this is my code, but in controller "get Instance" return null because of serialize data; how can i do this?

This is my controller:

<?php
public function actionUpdate($id)
    {
            $model = Signature::findOne([
                'user_id' => $id,
            ]);
            if ($model->load(Yii::$app->request->post())) {
                $model->file = UploadedFile::getInstance($model, 'file');
                $model->file->saveAs('uploads/signature/' . $model->user_id . '.' . $model->file->extension);
                $model->url = 'uploads/signature/' . $model->user_id . '.' . $model->file->extension;

                if ($model->save()) {
                    echo 1;
                } else {
                    echo 0;
                    echo $model->file;
                }
            } else {
                return $this->renderAjax('update', [
                    'model' => $model,
                ]);
            }
    }
?>

This is my script code I can't get my file in controller and it return null

<?php $script = <<<JS

$('form#{$model->formName()}').on('beforeSubmit', function(e)
{
    var $form = $(this);

    $.post(
    $form.attr("action"),
    $form.serialize(),

    )
        .done(function(result){
        if(result == 1)
        {
            $(document).find('#update_signature_modal').modal('hide');
            $.pjax.reload({container:'#branchesGrid'});
            //alert();
        } else {
            alert(result);
        }
        }).fail(function()
        {
            console.log("server error");
        });
        return false;
});

JS;
$this->registerJs($script);
?>

解决方案

Please refer here first

The Problem

What the problem in ajax is that $_FILES details are not sent in asynchroous request. When we submit the filled form without ajax request and debug in backend side in PHP by

echo '<pre>';
print_r($_FILES); 
print_r($_POST); 
echo '</pre>';
die; 

then we successfuly get $_FILES and $_POST data.

But when we debug the same thing in ajax request, we get only $_POST values and we get $_FILES as NULL. This led us to conclusion that $_FILES data are not sent in ajax request by our above code.

The Solution

We need to use FormData of JavaScript.

What does it do?

In simple words, it adds all necessary information of file which needs to be uploaded to data param in $.ajax OR fill up $_FILES as well as all $_POST data ie non file input such as strings number etc.

In your view file

<?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]) ?>
<?= $form->field($model, 'title') ?>
<?= $form->field($model, 'imageFile')->fileInput() ?>    
<button type="button" class="btn btn-success subm">Upload</button>
<?php ActiveForm::end(); ?>

<script>
$('.subm').click(function(e){
    var formData = new FormData($('form')[0]);
    console.log(formData);
    $.ajax({
        url: "some_php_file.php",  //Server script to process data
        type: 'POST',

        // Form data
        data: formData,

        beforeSend: beforeSendHandler, // its a function which you have to define

        success: function(response) {
            console.log(response);
        },

        error: function(){
            alert('ERROR at PHP side!!');
        },


        //Options to tell jQuery not to process data or worry about content-type.
        cache: false,
        contentType: false,
        processData: false
    });
});
</script>

Testing

Now make ajax request and debug in PHP code by print_r() as shown above, you will notice that $_FILES is not NULL and its contains all file (which needs to be uploaded) data. And if it is set you can upload using move_uploaded_file() funtion

So this is how you file is uploaded via Ajax.

Referece 1

Referece 2

Referece 3

相关文章