Yii2 对非对象调用成员函数saveAs()

Yii2 对非对象调用成员函数saveAs(),yii2,Yii2,我正在尝试上传图像和数据库表 在数据库表基本信息字段名“photo”中,我要存储文件名 这是模型 public function rules() { return [ [['photo'], 'string', 'max' => 255], [['image'], 'safe'], [['image'], 'file', 'extensions'=>'jpg, gif, png'],

我正在尝试上传图像和数据库表

在数据库表基本信息字段名“photo”中,我要存储文件名

这是模型

public function rules()
    {
        return [
            [['photo'], 'string', 'max' => 255],
            [['image'], 'safe'],
            [['image'], 'file', 'extensions'=>'jpg, gif, png'],
        ];
    }
这是控制器

 public function actionCreate()
        {
            $model = new BasicInfo();


           if ($model->load(Yii::$app->request->post()))
            {

                $model->image = UploadedFile::getInstance($model, 'image');
                $filename = pathinfo($model->image , PATHINFO_FILENAME);
                $ext = pathinfo($model->image , PATHINFO_EXTENSION);

                $newFname = $filename.'.'.$ext;
                $path=Yii::getAlias('@membersImgPath');

                    if(!empty($newFname)){
                        $model->image->saveAs($path.$newFname);
                        $model->image = $newFname;
                        if($model->save()){
                        return $this->redirect(['view', 'id' => $model->id]);
                        }
                    }

                }
                    return $this->render('create', [
                        'model' => $model,
                ]);
        }
这里是观景台

echo FileInput::widget([
    'name' => 'photo', 
    'options' => ['accept' => 'image/*'],
]);

从你在这里的评论来看

$form=ActiveForm::begin['type'=>ActiveForm::type\u VERTICAL],'opti‌​ons'=>['enctype'=>'m‌​多部件/表格数据']‌​];

ActiveForm::begin没有第二个参数。您需要使用单个选项数组

$form = ActiveForm::begin([
    'type'    => ActiveForm::TYPE_VERTICAL,
    'opti‌​ons' => [
        'enctype' => 'm‌​ultipart/form-data'
    ]‌
​]);

首先,您必须检查是否存在文件。要执行此操作,请尝试:

if(UploadedFile::getInstance($model, 'image')) {
     // here should go your code with $model->image
}
您使用的是pathinfo获取文件名和扩展名。请记住,您使用的是powerfull framework,您只是初始化了类UploadedFile,它可以为您做任何事情:

if(UploadedFile::getInstance($model, 'image')) {
     $model->image = UploadedFile::getInstance($model, 'image');
     $newFname = $model->image->name;     // UploadedFile have properties like `name`, `tempName`, even `size`!
}
在对您的代码进行了这些小的修复之后,您应该始终检查是否设置了某些内容-我们可以转到主要问题

您的输入字段名为photo,但您正在尝试使用名称image获取图像

更改此项:

UploadedFile::getInstance($model, 'image');
为此:

UploadedFile::getInstance($model, 'photo');   // remeber to change it in `if` statement aswell!!

还有一种可能性是,您尝试上载的文件可能大于您的post_max_大小,并且上载的文件大小不允许。请在php.ini中更改此属性,重新启动服务器并重试。如果仍然有问题,请尝试调试此问题,首先在控制器中执行var_dump$_FILES;die;。

您有什么问题吗?是否发布g文件也可以吗?你能发布包含ActiveForm::begin的文件吗?那么…检查$model->image返回的内容。你的表单是否设置了enctype参数?遵循指南是的,我设置了enctype。如何检查$model->image像所有变量一样,var_dump$var;