我使用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,
]);
}
答案 0 :(得分:1)
更改您的控制器文件,如....
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,
]);
}
答案 1 :(得分:0)
我只是从行中删除image_path
:
[['name', 'price', 'description', 'image_path'], 'required'],
现在好了。