Файл не загружается в yii2

Я хочу загрузить изображение и сохранить его в своей базе данных. Здесь имя поля в базе данных image_path. Когда я пытаюсь загрузить свое изображение, оно показывает ошибку: вызов функции-члена saveAs() для необъекта в строке

$customer->file->saveAs('uploads/customer/' . $customer->file->baseName . '.' . $customer->file->extension);

Если я напечатаю var_dump($customer->file);, он вернет NULL.

Может ли кто-нибудь помочь мне решить эту проблему.

Это мое мнение:

    <?php $form = ActiveForm::begin([
            'id' => 'my-profile',
            'action' => \Yii::$app->urlManager->createUrl(['/myprofile', 'id_customer' => Yii::$app->user->identity->id_customer]),                     
            'options' => ['enctype'=>'multipart/form-data']
    ]); ?>
    <?= $form->field($customer, 'file')->fileInput() ?>
    <?php ActiveForm::end(); ?>

Это моя модель:

public $file;
public function rules()
{
    return [
        ['active', 'default', 'value' => self::STATUS_ACTIVE],
        ['active', 'in', 'range' => [self::STATUS_ACTIVE, self::STATUS_DELETED]],            
        [['file'],'file'],
        [['name', 'image_path'], 'string', 'max' => 200],            
    ];
}

public function attributeLabels()
{
    return [            
        'file' => 'Profile Picture ',            
    ];
}

Это мой контроллер:

public function actionMyprofile(){   

  $customer->file = UploadedFile::getInstance($customer,'image_path');      
  $customer->file->saveAs('uploads/customer/' . $customer->file->baseName . '.' . $customer->file->extension);
  $customer->file = 'uploads/customer/' . $customer->file->baseName . '.' . $customer->file->extension;
}

person Subhankar Bhattacharjee    schedule 14.12.2015    source источник
comment
Замените image_path на file в контроллере, см. правила вашей модели.   -  person Insane Skull    schedule 14.12.2015
comment
UploadedFile::getInstance($customer,'image_path'); должно быть UploadedFile::getInstance($customer,'file');, так как <?= $form->field($customer, 'file')->fileInput() ?>   -  person ineersa    schedule 14.12.2015
comment
Я задаю вопрос несколько дней назад, но не получил точного ответа   -  person Anway Kulkarni    schedule 14.12.2015
comment
stackoverflow.com/questions/33119257/   -  person Anway Kulkarni    schedule 14.12.2015
comment
После этого он остается прежним.   -  person Subhankar Bhattacharjee    schedule 14.12.2015
comment
Пожалуйста, покажите var_dump(ini_get('file_uploads')), var_dump($_FILES)   -  person SilverFire    schedule 14.12.2015
comment
Установите полный путь в функции saveAs с псевдонимом.   -  person stig-js    schedule 15.12.2015


Ответы (1)


Просмотр:

<?php $form = ActiveForm::begin([
        'id' => 'my-profile',
        'action' => \Yii::$app->urlManager->createUrl(['/myprofile', 'id_customer' => Yii::$app->user->identity->id_customer]),                     
        'options' => ['enctype'=>'multipart/form-data']
]); ?>
<?= $form->field($customer, 'image_path')->fileInput() ?>
<?php ActiveForm::end(); ?>

Модель:

public function rules()
{
  return [
    ['active', 'default', 'value' => self::STATUS_ACTIVE],
    ['active', 'in', 'range' => [self::STATUS_ACTIVE, self::STATUS_DELETED]],            
    [['image_path'],'file'],
    [['name', 'image_path'], 'string', 'max' => 200],            
  ];
}

public function attributeLabels()
{
   return [            
       'image_path' => 'Profile Picture ',            
   ];
}

Контроллер:

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

    if ($model->load(Yii::$app->request->post())) {
        $model->image_path = UploadedFile::getInstance($model, 'image_path');

        $filename = pathinfo($model->image_path , PATHINFO_FILENAME);
        $ext = pathinfo($model->image_path , PATHINFO_EXTENSION);

        $newFname = $filename.'.'.$ext;

        $path=Yii::getAlias('@webroot').'/image/event-picture/';
        if(!empty($newFname)){
            $model->image_path->saveAs($path.$newFname);
            $model->image_path = $newFname; 
            if($model->save()){
                return $this->redirect(['your redirect_path', 'id' => $model->id]);
            }       
        }           
    } 
    return $this->render('create', [
        'model' => $model,
    ]);
}
person vishuB    schedule 15.12.2015