Following Yii Framework 2.0 documentation http://www.yiiframework.com/doc-2.0/guide-input-file-upload.html I tried to upload image. The image could be uploaded successfully, but after uploading the image, I tried to insert the model into the database with the following code.
$model->file->saveAs('uploads/' . $model->file->baseName . '.' . $model->file->extension);
$model->save();
I got the following error:
PHP Warning – yii\base\ErrorException
finfo_file(/tmp/phpIGuwiT): failed to open stream: No such file or directory
1. in /var/www/html/website/advanced/vendor/yiisoft/yii2/helpers/BaseFileHelper.php
if ($info) {
$result = finfo_file($info, $file);
finfo_close($info);
if ($result !== false) {
return $result;
}
}
2. in /var/www/html/my-project/advanced/vendor/yiisoft/yii2/validators/FileValidator.php – yii\helpers\BaseFileHelper::getMimeType()
$mimeType = FileHelper::getMimeType($file->tempName, null, false);
3.
4.
and so on ....
The result is that image has been uploaded but the model has not been inserted into the database. Does anyone know how to solve this?
Replace
$model->save()
by
$model->save(false)
This is because when you perform $model->save() with no argument, it will by default consider
true
ie the input must be validated (reference). And all inputs must be validated before uploading or saving in database ie aboveline and
line
So finally my suggestion is
In your XyzController.php (in "create" (actionCreate possibly) scenario)
This would work fine in create scenario, but what about "update" (actionUpdate possibly) scenario? In that case I have tested Aleksandr Ivin's (above) answer and it's working fine. Here is the description
If image uploading is not mandatory than
This issue can be caused by two issues, not just what is stated in other answers:
You can change it by editing your php.ini file settings:
Make sure
post_max_size
is bigger than or equal toupload_max_file_size
andmemory_limit
is bigger than or equal topost_max_size
.Here is a practical and real life example of how you would use it in your controller:
when we save to image field in db, just use
when you try to print $model->file you will get an array
I was having same same problem, I solve with this.
$model->file->saveAs($filepath , false)
then
$model->save(false)
Important : in
saveAs
function passFalse
parameter.Do as follows
Hope this helps!