M
M
Maxim2017-10-06 22:47:02
Yii
Maxim, 2017-10-06 22:47:02

How to upload and update images in Yii?

Hello! Can you please tell me how to save images in Yii2? Declared an additional $file variable and added loading code to the model after saving. There is data in the debugger, but it is not loaded into the root and database ...
Loading code

public function beforeSave($insert)
    {
        if ($file = UploadedFile::getInstance($this, 'file')){
            $dir = Yii::getAlias('@images').'/trener/';
            if (file_exists($dir.$this->img)){
                unlink($dir.$this->img);
            }
            if (file_exists($dir.'50x50/'.$this->img)){
                unlink($dir.'50x50/'.$this->img);
            }
            if (file_exists($dir.'/800x/'.$this->img)){
                unlink($dir.'800x/'.$this->img);
            }
            $this->img = strtotime('now').Yii::$app->getSecurity()->generateRandomString(6) . '.' .$file->extension;
            $file->saveAs($dir.$this->img);

        }
        return parent::beforeSave($insert); // TODO: Change the autogenerated stub
    }

Form field
<?= $form->field($model, 'img')->widget(FileInput::classname(), [
        'pluginOptions' => [
            'showCaption' => false,
            'showRemove' => false,
            'showUpload' => false,
            'browseClass' => 'btn btn-primary btn-block',
            'browseIcon' => '<i class="glyphicon glyphicon-camera"></i> ',
            'browseLabel' =>  'Выбрать изображение'
        ],
        'options' => ['accept' => 'image/*']
    ]) ?>

I would also like to know the code for loading into the form when updating

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Maxim Timofeev, 2017-10-07
@myks92

You added the file variable, and in the form you use img, but at the same time you are trying to save a picture from file, in which it is clearly null, replace:
with
Well, here's the stupidity:
You don't have a file name in $this->img, it's null. So if you want to save with the name that the file had, then apparently like this:

$name = $file->baseName . '.' . $file->extension; //формируем имя и расширение
if($file->saveAs($dir.$name)){ //проверяем сохранилось ли
  $this->img = $name; //если сохранилось записываем имя в атрибут, который сохранит имя в базу
}

D
Dmitry, 2017-10-07
@slo_nik

Goodnight.
You're using beforeSave() a little differently;

public function beforeSave($insert)
    {
      if(parent::beforeSave($insert)){
          if ($file = UploadedFile::getInstance($this, 'file')){
              $dir = Yii::getAlias('@images').'/trener/';
              if (file_exists($dir.$this->img)){
                  unlink($dir.$this->img);
              }
              if (file_exists($dir.'50x50/'.$this->img)){
                unlink($dir.'50x50/'.$this->img);
              }
              if (file_exists($dir.'/800x/'.$this->img)){
                unlink($dir.'800x/'.$this->img);
              }
              $this->img = strtotime('now').Yii::$app->getSecurity()->generateRandomString(6) . '.' .$file->extension;
              $file->saveAs($dir.$this->img);
         }     
          return true;
      }
      return false
    }

PS
In bourgeois
In native language)))))

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question