在yii2中上传Ajax文件 [英] Upload Ajax file in yii2
问题描述
我想在yii2框架中使用Ajax上传文件 这是我的代码,但是由于序列化数据,在控制器获取实例"中返回null;我该怎么办?
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?
这是我的控制者:
<?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,
]);
}
}
?>
这是我的脚本代码 我无法在控制器中获取文件,并且它返回null
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);
?>
推荐答案
ajax中的问题是$_FILES
详细信息未在非同步请求中发送.
当我们提交没有ajax请求的填写好的表单并在PHP的后端调试时,
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;
然后我们成功获取$_FILES
和$_POST
数据.
then we successfuly get $_FILES
and $_POST
data.
但是当我们在ajax请求中调试相同的东西时,我们仅获得$_POST
值,并且获得$_FILES
作为NULL
.这导致我们得出结论,上述代码未在ajax请求中发送$_FILES
数据.
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.
解决方案
我们需要使用JavaScript的 FormData
.
We need to use FormData
of JavaScript.
它是做什么的?
简单地说,它将所有需要上传的文件的所有必要信息添加到$.ajax
中的data
参数中,或填充$_FILES
以及所有$_POST
数据,即非文件输入,例如字符串号等
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.
在您的视图文件中
<?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>
测试
现在,如上所示,通过print_r()
发出ajax请求并在PHP代码中进行调试,您将注意到$_FILES
不是NULL,它包含所有文件(需要上传)数据.如果已设置,则可以使用move_uploaded_file()
功能
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
这就是您通过Ajax上传文件的方式.
So this is how you file is uploaded via Ajax.
这篇关于在yii2中上传Ajax文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!