在 Yii2 中上传图片和验证

Uploading image and Validation in Yii2

我正在使用 Yii2 创建一个简单的上传图片并验证图片扩展。我读过 Yii2 文档,但我不知道 $model->validate() 总是 return false。对我有什么想法吗?

在我的模型文件中,我为 imageFile:

设置了规则
public function rules()
    {
        return [
            [['name', 'price', 'description', 'image_path'], 'required'],
            [['price'], 'integer'],
            [['description'], 'string'],
            [['name', 'image_path'], 'string', 'max' => 255],
            [['imageFile'], 'image', 'skipOnEmpty' => false, 'extensions' => 'png, jpg, jpeg'],
        ];
    }

在我的操作中控制器索引:

if ($model->load(Yii::$app->request->post())) {
    $model->imageFile = UploadedFile::getInstance($model, 'imageFile');
    if ($model->validate() && $model->save()) {
        $model->imageFile->saveAs('uploads/' . Yii::$app->params['bonuslyRewards'] . '/' . $model->imageFile->baseName . '.' . $model->imageFile->extension);
        $model->image_path = 'uploads/' . Yii::$app->params['bonuslyRewards'] . '/' . $model->imageFile->baseName . '.' . $model->imageFile->extension;
        return $this->redirect(['view', 'id' => $model->id]);
            }
    } else {
      return $this->render('create', [
            'model' => $model,
        ]);
    }

更改您的控制器文件,例如...

 if ($model->load(Yii::$app->request->post())) 
 {
   $model->imageFile = UploadedFile::getInstance($model, 'imageFile');          
   $path=Yii::getAlias('@webroot').'/your Path/';
   if(!empty($model->imageFile)){
        $model->imageFile->saveAs($path.$model->imageFile);
   }    
   if($model->save()){
      return $this->redirect(['view', 'id' => $model->id]);
   }
 }
 return $this->render('create', [
        'model' => $model,
    ]);
}

我只是从行中删除 image_path

[['name', 'price', 'description', 'image_path'], 'required'],

现在可以了