我正在尝试在Yii2中运行一个应用程序
我试图上传一个用户个人资料图片,它工作得很好
但是当我尝试更新名称文件时,问题就出现了。它显示了像Call to a member function saveAs() on a non-object
这样的错误。
我甚至试图更新,没有任何改变..即使那个时间也给我显示相同的错误...
但是如果我改变图片就会出错。
这是我的控制器
public function actionUpdate($id)
{
$model = $this->findModel($id);
if ($model->load(Yii::$app->request->post()) && $model->save()) {
// get the instance of uploaded file
$imageName = $model->user_username;
$model->file = UploadedFile::getInstance($model,'user_avatar');
$model->file->saveAs( '/uploads/'.$imageName.'.'.$model->file->extension );
//save the path in DB..
$model->user_avatar = 'uploads/'.$imageName.'.'.$model->file->extension;
$model->save();
return $this->redirect(['view', 'id' => $model->user_id]);
} else {
return $this->render('update', [
'model' => $model,
]);
}
}
模型规则
public function rules()
{
return [
[['user_email', 'user_password'], 'required'],
// [['user_password'], 'required'],
[['user_username'], 'string', 'max' => 45],
[['user_first_name'], 'required'],
[['user_app_user_id'], 'required',
[['user_type','user_app_name','user_status'], 'string'],
[['user_app_user_id'], 'integer'],
[['user_rememberMe'], 'boolean'],
[['user_first_name', 'user_last_name'], 'string', 'max' => 100],
[['user_email'], 'string', 'max' => 150],
[['user_password'], 'string', 'min'=>6],
[['user_password'], 'string', 'max' => 40,
[['user_avatar'],'file'],
//[['user_avatar'], 'string', 'max' => 500],
[['user_verification_code','user_auth_key'], 'string'],
[['user_email'], 'email'],
[['user_email'], 'filter', 'filter' => 'trim'],
];
}
答案 0 :(得分:3)
您的代码需要上传文件。你应该在这里添加条件:
if ($model->file = UploadedFile::getInstance($model,'user_avatar')) {
$model->file->saveAs( '/uploads/'.$imageName.'.'.$model->file->extension );
//save the path in DB..
$model->user_avatar = 'uploads/'.$imageName.'.'.$model->file->extension;
$model->save();
}
答案 1 :(得分:0)
试试这个..
$model->file = UploadedFile::getInstance($model,'user_avatar');
$ext = substr(strrchr($model->file,'.'),1);
if($ext != null)
{
$newfname = $model->user_username.'.'.$ext;
$model->file->saveAs(Yii::getAlias('@webroot') .'/uploads/' .$model->user_avatar = $newfname);
}
答案 2 :(得分:0)
我不确定这是否正确,但同时我们只需要取消设置 img 模型所需的规则:
命名空间应用\模型;
[['img','post_img'], 'required'], -<<<<Delete this
在删除要求规则后,我的麻烦就消失了。希望能对某人有所帮助。