YII2图像提交



我正在尝试在数据库中注册2个上传的图像,然后将其上传到'上传'文件夹。它给了我#400不良请求,如"无法验证您的数据提交"。有想法该怎么解决这个吗?以下是我的代码。

Controller actionCreate():
public function actionCreate()
{
    $model = new PhotoCategories();
    if ($model->load(Yii::$app->request->post())) {
        $model->image = UploadedFile::getInstance($model, 'image');
        $model->thumbnail_image = UploadedFile::getInstance($model, 'thumbnail_image');
        if ($model->upload()) {
            $model->save();
        }
        return $this->redirect(['view', 'id' => $model->id]);
    } else {
        return $this->render('create', [
            'model' => $model,
        ]);
    }
}

模型使用ImageValidator。这是规则((和upload((函数:

    public function rules()
    {
        return [
            [['name', 'thumbnail_image', 'image', 'description'], 'required'],
            [['description'], 'string'],
            [['name'], 'string', 'max' => 256],
            [['name'], 'unique'],
            [['thumbnail_image'], 'image', 'skipOnEmpty' => false, 'extensions' => 'png, jpg'],
            [['image'], 'image', 'skipOnEmpty' => false, 'extensions' => 'png, jpg']
        ];
    }
    public function upload() {
        if ($this->validate()) {
            $this->image->saveAs('uploads/' . $this->image->baseName . '.' . $this->image->extension);
            $this->thumbnail_image->saveAs('uploads/' . $this->image->baseName . '.' . $this->image->extension);
            return true;
        } else {
            return false;
        }
    }

表格的视图文件如下:

<div class="photo-categories-form">
    <?php $form = ActiveForm::begin(); ?>
    <input type="hidden" name="<?= Yii::$app->request->csrfParam; ?>" value="<?= Yii::$app->request->csrfToken; ?>" />
    <?= $form->field($model, 'name')->textInput(['maxlength' => true]) ?>
    <?= $form->field($model, 'thumbnail_image')->fileInput() ?>
    <?= $form->field($model, 'image')->fileInput() ?>
    <?= $form->field($model, 'description')->textarea(['rows' => 6]) ?>
    <div class="form-group">
        <?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
    </div>
    <?php ActiveForm::end(); ?>
</div>

即使我也写了隐藏的输入,但它仍然给我带来了错误。

yii不允许CSRF是跨站点请求伪造的缩写。因此,如果您要禁用CSRF检查,请在控制器中添加以下代码

public $enableCsrfValidation = false;

有关更多信息,请参阅此信息。http://www.yiiframework.com/doc-2.0/guide-security-best-practices.html#avoiding-csrf

警告:禁用CSRF将允许任何网站将发布请求发送到您的网站。在这种情况下,实施额外验证,例如检查IP地址或秘密令牌很重要。

您需要在表单内部设置为输入值。

<input type="hidden" name="<?= Yii::$app->request->csrfParam; ?>" value="<?= Yii::$app->request->csrfToken; ?>" />

注意: - 这是处理"无法验证数据提交"的更好方法。错误。

最新更新