Answer the question
In order to leave comments, you need to log in
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($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/*']
]) ?>
Answer the question
In order to leave comments, you need to log in
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; //если сохранилось записываем имя в атрибут, который сохранит имя в базу
}
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
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question