@XciloG

Ошибка Bad Request (#400): Unable to verify your data submission. при загрузке файлов c использованием расширения bootstrap-fileinput?

Установил расширение
В view добавил код
<input id="input-ru-1" type="file" multiple class="file-loading">
            <script>
                $("#input-ru-1").fileinput({
                    language: "ru",
                    uploadUrl: "index.php?r=site/upload&id=1",
                    allowedFileExtensions: ["jpg"]
                });
            </script>


В Action контроллера написал

public function actionUpload()
    {


            $model = new Images();

            if (empty($_FILES['file_data'])) {
                $output = ['error'=>'No files found for upload.'];
                return $this->render('upload', ['message'=> $output]);
            }

            //$images = $_FILES['file_data'];


            $success = null;
            $paths= [];

            $filename = md5(uniqid()) . ".jpg";
            $target = "uploads" . DIRECTORY_SEPARATOR . $_GET['id'] . DIRECTORY_SEPARATOR . $filename ;

            if(move_uploaded_file($_FILES['file_data']['tmp_name'], $target)) {
                $success = true;
                $paths[] = $target;
            } else {
                $success = false;
            }

            if ($success === true) {

                $model->created_at = time();
                $model->updated_at = time();

                $model->type = $_GET['id'];

                $model->file_name = $filename;

                if ($model->save()) {$output = [];} else  {$output = ['error'=>'Ошибка сохранения в БД'];}

            } elseif ($success === false) {
                $output = ['error'=>'Error while uploading images. Contact the system administrator' .$target];
                foreach ($paths as $file) {
                    unlink($file);
                }
            } else {
                $output = ['error'=>'No files were processed.'];
            }

       //      return $this->render('upload', ['message'=>$output]);

                Yii::$app->response->format = 'json';
                return $output;
        }


При загрузке файлов ошибка Bad Request (#400): Unable to verify your data submission.

Все работает если в контроллере отключить проверку CSRF, но это не лучший вариант.
public $enableCsrfValidation = false;

Как передать CSRF в контроллер вместе с файлами не могу понять?
  • Вопрос задан
  • 606 просмотров
Решения вопроса 1
@XciloG Автор вопроса
Разобрался, может кому поможет, передается этот параметр через uploadExtraData
$("#input-ru-1").fileinput({
                    language: "ru",
                    uploadUrl: "index.php?r=site/upload&id=1",
                    allowedFileExtensions: ["jpg"],
                    uploadExtraData: {_csrf: '<?=Yii::$app->request->getCsrfToken()?>'}
                });
Ответ написан
Комментировать
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы