I'm trying to use this widget https://github.com/kartik-v/yii2-widget-fileinput .
When I click the download button, I get the SyntaxError error: Unexpected token <in JSON at position 0. But if I click save, the image is saved in the database and in my uploads folder. Tell me please what’s wrong? I myself can not fix it in any way
models / Photo.php
... public function rules() { return [ [['img'], 'required'], [['file'],'file','maxSize' => '5242880' ], // 'extensions' => 'jpg' [['img'], 'string', 'max' => 255], ]; } ...
PhotoController.php
... public function actionUpdate($id) { $model = $this->findModel($id); if ($model->load(Yii::$app->request->post())) { $imageName = rand(1000,100000); $model -> file = UploadedFile::getInstance($model, 'file'); $model -> file -> saveAs('uploads/'.$imageName.'.'.$model->file->extension); $model -> img = '@web/uploads/'.$imageName.'.'.$model->file->extension; $model->save(); if ($model->save()) { \Yii::$app -> response -> format = \yii\web\Response::FORMAT_JSON; $result = []; return $result; // return $this->redirect(['view', 'id' => $model->id]); } } else { return $this->render('update', [ 'model' => $model, ]); } } ...
view / update.php
<?php use yii\helpers\Html; //use yii\widgets\ActiveForm; use kartik\file\FileInput; use kartik\form\ActiveForm; use yii\helpers\Url; /* @var $this yii\web\View */ /* @var $model app\modules\user\models\Photo */ /* @var $form yii\widgets\ActiveForm */ ?> <div class="photo-form container"> <?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]); ?> <!-- --><?//= $form->field($model, 'file')->fileInput(); ?> <?= $form->field($model, 'file')->widget(FileInput::classname(), [ 'options' => ['accept'=>'image/*'], 'pluginOptions'=>[ 'uploadUrl' => Url::to(['/uploads']), 'allowedFileExtensions'=>['jpg', 'gif', 'png'], 'showUpload' => true, 'initialPreview' => [ // $model-> img ? Html::img($model-> img) : null, // checks the models to display the preview ], 'overwriteInitial' => false, ], ]); ?> <div class="form-group"> <?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?> </div> <?php ActiveForm::end(); ?> </div>
return $this->redirect(['index']);
which is clearly not. - Ninazu