【问题标题】:Uploading image and Validation in Yii2在 Yii2 中上传图片和验证
【发布时间】:2016-02-02 03:00:02
【问题描述】:

我正在使用 Yii2 创建一个简单的上传图片并验证图片扩展。我读过 Yii2 文档,但我不知道 $model->validate() 总是返回 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,
        ]);
    }

【问题讨论】:

  • 因为image_path 是必需的。
  • $model->image_path之后添加if($model->save()) {return $this->redirect(['view', 'id' => $model->id]); }
  • 没错,image_path 是必需的。

标签: php validation yii2 image-uploading


【解决方案1】:

我只是从行中删除image_path

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

现在好了。

【讨论】:

    【解决方案2】:

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

     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,
        ]);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-05-28
      • 2017-07-25
      • 1970-01-01
      • 1970-01-01
      • 2015-03-13
      • 1970-01-01
      • 2017-04-28
      • 2016-05-26
      相关资源
      最近更新 更多