[英]Upload Ajax file in yii2
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; 我想在yii2框架中使用Ajax上传文件这是我的代码,但是在控制器“get Instance”中因为序列化数据而返回null; 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 这是我的脚本代码我无法在控制器中获取我的文件,它返回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. ajax中的问题是
$_FILES
细节不会在异步请求中发送。 When we submit the filled form without ajax request and debug in backend side in PHP by 当我们在没有ajax请求的情况下提交填充的表单并在PHP的后端进行调试时
echo '<pre>';
print_r($_FILES);
print_r($_POST);
echo '</pre>';
die;
then we successfuly get $_FILES
and $_POST
data. 然后我们成功获得
$_FILES
和$_POST
数据。
But when we debug the same thing in ajax request, we get only $_POST
values and we get $_FILES
as NULL
. 但是当我们在ajax请求中调试相同的东西时,我们只得到
$_POST
值,并且$_FILES
为NULL
。 This led us to conclusion that $_FILES
data are not sent in ajax request by our above code. 这导致我们得出结论,
$_FILES
数据不是由我们的上述代码在ajax请求中发送的。
The Solution 解决方案
We need to use FormData
of JavaScript. 我们需要使用JavaScript的
FormData
。
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. 简单来说,它添加了需要上传到
$.ajax
data
参数的文件的所有必要信息,或者填写$_FILES
以及所有$_POST
数据,即非文件输入,例如字符串编号等。
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. 现在通过
print_r()
在PHP代码中进行ajax请求和调试,如上所示,你会注意到$_FILES
不是NULL并且它包含所有文件(需要上传的)数据。 And if it is set you can upload using move_uploaded_file()
funtion 如果已设置,您可以使用
move_uploaded_file()
函数上传
So this is how you file is uploaded via Ajax. 这就是你通过Ajax上传文件的方式。
Use FormData to get the instance of file/image type data 使用FormData获取文件/图像类型数据的实例
$( '#my-form' )
.submit( function( e ) {
$.ajax( {
url: 'http://host.com/action/',
type: 'POST',
data: new FormData( this ),
processData: false,
contentType: false
} );
e.preventDefault();
} );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.