yii2yii2-basic-app

data not saving in database with fileupload in yii2


File uploading to uploads folder but not saving in the database, getting below error

Unknown Method – yii\base\UnknownMethodException Calling unknown method: app\models\UploadForm::save()

Below is my controller code

$name =  $model->file->baseName . '.' .$model->file->extension;

$file = new UploadForm();
$file->image_name = $name;
$file->image_path = $name;
$file->save();

This is my model code

namespace app\models;

use yii\base\Model;
use yii\web\UploadedFile;

  public function rules()
    {
        //echo "in";
        return [
           [['image'], 'file', 'skipOnEmpty' => false, 'extensions' => 'png, jpg, jpeg'],
           ['image_path','string'],
        ];
    }

Can anyone help me? I am new to yii2


Solution

  • Can you try below code ?

    use yii\web\UploadedFile;
    $file = UploadedFile::getInstanceByName('Image Input Field Name');
    if (!empty($file) && $file->extension != '') {
        $newFileName = rand() . '.' . $file->extension; 
        if ($file->saveAs($uploadPath . '/' . $newFileName)) {
        
            // another code
        }
    }