尝试在Yii2中使用kartik-v进行图像上传时获取非对象的属性

时间:2016-08-18 05:35:02

标签: yii2 image-uploading

我使用yii2-widget-fileinput在表单中上传图片。 当我点击上传或创建按钮时,我在控制器中出现Trying to get property of non-object错误。

控制器

public function actionCreate()
    {
        Yii::$app->params['uploadPath'] = Yii::$app->basePath . '/uploads/';
        $model = new Ads();
        $provinces = ArrayHelper::map(Province::find()->all(), 'name', 'name'); 
        if ($model->load(Yii::$app->request->post())){

            $image = UploadedFile::getInstances($model, 'image');
            $model->filename = $image->name;
            $ext = end((explode(".", $image->name)));
            $avatar = Yii::$app->security->generateRandomString().".{$ext}";
            $path = Yii::$app->params['uploadPath'].$avatar;
            if ($model->save()) {

                $image->saveAs($path);
                $model->image_adr = $path;
                return $this->redirect(['view', 'id' => $model->id]);
            }else{
                echo "error on saving the model";
            }

        }
        return $this->render('create', [
            'model' => $model,
            'provinces'=>$provinces,
            ]);
    }

模型规则

public function rules()
    {
        return [
            [['type', 'explanation', 'cost', 'province_name', 'address'], 'required'],
            [['type', 'explanation', 'image_adr', 'address'], 'string'],
            [['cost'], 'integer'],
            [['province_name'], 'string', 'max' => 20],
            [['province_name'], 'exist', 'skipOnError' => true, 'targetClass' => Province::className(), 'targetAttribute' => ['province_name' => 'name']],
            [['image'],'safe'],
            [['image'], 'file', 'extensions'=>'jpg, gif, png', 'maxFiles'=>3,],
        ];

最后是视图

    <?= $form->field($model, 'image[]')->widget(FileInput::classname(), [
    'options'=>['accept'=>'image/*', 'multiple'=>true],
    'pluginOptions'=>['allowedFileExtensions'=>['jpg','gif','png'], 'overwriteInitial'=>false,]
            ]); ?>

问题应该参考我认为控制器中的这部分

$image = UploadedFile::getInstances($model, 'image');  

错误的图像可能会有所帮助

property of non-object error

2 个答案:

答案 0 :(得分:1)

你应该首先检查是否是邮件中的图像。

....

$image = UploadedFile::getInstances($model, 'image'); //getInstanceByName

if (!empty($image))
   $model->filename = $image->name;

  .....
  if ($model->save()) {
        if (!empty($image))
                $image->saveAs($path);
.........

确保在表单中添加了ency类型:

$form = ActiveForm::begin([ 
'id' => 'form_id', 
'options' => [ 
'class' => 'form_class', 
'enctype' => 'multipart/form-data', 
], 
]); 

答案 1 :(得分:0)

问题在于,当您使用UploadedFile::getInstances($model, 'image');时,您应该使用foreach或将其视为数组。

让我遇到问题的是,即使你正在使用UploadedFile::getInstanc (注意最后的废弃s),你仍然应该像对待数组一样对待它您应该使用的所有部分$image[0],而不是$iamge孤独。