我有一个使用Ajax POST的activeform,并且正在发送表单字段,但是似乎文件数据没有发送。 这是我文件中与逻辑相关的代码片段,它们下面是使用JS警报和结果的测试注释
ActiveForm:
<?= $form->field($model, 'userphoto')->fileInput() ?>
Ajax提交:
$script = <<< JS
$('form#{$model->formName()}').on('beforeSubmit', function(event)
{
event.preventDefault();
var form = $(this);
formdata = new FormData(form[0]);
$.ajax({
url : form.attr('action'),
data : formdata,
cache : false,
contentType : false,
processData : false,
type : 'POST',
success: function (response)
{
alert(JSON.stringify(response.status);
$.pjax.reload({container:'#usergrid'});
$(form).trigger('reset');
},
});
return false;
});
JS;
$this->registerJs($script);
?>
型号:
use yii\web\UploadedFile;
class Usermanager extends \yii\db\ActiveRecord
{
public static function tableName()
{
return 'user';
}
public $userphoto;
public function rules()
{
return [
[['userphoto'], 'file', 'extensions' => 'jpg, png, gif',
'skipOnEmpty' => true],
控制器:
namespace app\controllers;
use Yii;
use app\models\Usermanager;
use yii\web\Controller;
use yii\web\Response;
use yii\web\UploadedFile;
class UsermanagerController extends Controller
{
public function actionCreate()
{
$model = new Usermanager();
if(Yii::$app->request->isAjax && $model->load(Yii::$app->request->post()) && Yii::$app->request->enableCsrfValidation)
{
Yii::$app->response->format = 'json';
$userphoto = UploadedFile::getInstance($model, 'userphoto');
/* return ['status' => $userphoto]; */
$model->photo = "web/". $model->username. "." .$userphoto->extension;
if($model->password !==''){
$model->password = Yii::$app->security->generatePasswordHash($model->password);
}
if($model->validate())
{
$model->save();
}
else
{
return ActiveForm::validate($model);
}
}
return $this->renderAjax('create', [
'model' => $model
]);
}
这是JS警报测试结果:
测试-(控制器收到POST)
$userphoto = UploadedFile::getInstance($model, 'userphoto');
return ['status' => $userphoto];
测试结果->警报(JSON.stringify(response.status)):
{"name":"kde.jpg","tempName":"/tmp/phpjp3i4d",
"type":"image/jpeg","size":51253,"error":0}
您可以看到警报详细说明了文件属性,就像收到文件一样。但是,如果尝试以此方式获取文件扩展名,则:
$model->photo = "web/". $model->username. "." .$userphoto->extension;
找不到扩展名。此外,我还尝试过使用$ userphoto-> saveAs保存,但是console.log报告无法保存null()。
那么,有没有人使用YII2成功集成了AJAX提交和文件上传功能,而可能没有使用Kartik小部件?