Moeez
Moeez

Reputation: 478

Yii2 - How to upload & store Images in Database

I am using yii2. I am trying to select a file and then want to save it to my database table. I am using core PHP for it. Below is my code

<form action = <?=\yii\helpers\Url::toRoute(['meteracceptanceheader/import'])?> method ="post"
           enctype="multipart/form-data">
.
.
.
.
.
.
.

<div class="row">
                <div class="col-md-2">

                    Upload-Image
                    <input type="file" name="file"/>
                    <br />
                    <input type="submit" class="btn btn-primary pull-left"  />
                </div>
            </div>
</form>

Controller

public function actionImport()
{

    .
    .
    . // my other code

    $file = $_FILES['file'];
    $fileName = $_FILES['file']['name'];
    $fileExt = explode('.',$fileName);
    print_r($file);
    die();
    .
    .
    .
    .

return $this->render('excel_finish', ['records_saved' => $ok_count,'status_arr'=>$status_arr]);
}

Database Table

enter image description here

In the above table, id is auto-increment accpt_id is the model id which I already have and file_path is the name of the file which should be saved like 123.jpg.

The file should be saved into a folder uploads/meter_acceptance/ and append with the file name.

Note:

I have already know how to upload images via the active form but here I want to do it in a traditional way.

Any help would be highly appreciated.

Upvotes: 0

Views: 2928

Answers (1)

Bira
Bira

Reputation: 5506

your controller should be like this

public function actionUpload(){

    $model = new Images();
    $uploadPath = Yii::getAlias('@root') .'/uploads/';

    if (isset($_FILES['image'])) {
        $file = \yii\web\UploadedFile::getInstanceByName('image');
      $original_name = $file->baseName;  
      $newFileName = \Yii::$app->security
                        ->generateRandomString().'.'.$file->extension;
       // you can write save code here before uploading.
        if ($file->saveAs($uploadPath . '/' . $newFileName)) {
            $model->image = $newFileName;
            $model->original_name = $original_name;
            if($model->save(false)){
                echo \yii\helpers\Json::encode($file);
            }
            else{
                echo \yii\helpers\Json::encode($model->getErrors());
            }

        }
    }
    else {
        return $this->render('upload', [
            'model' => $model,
        ]);
    }

    return false;
}

Upvotes: 2

Related Questions