you can easily implement a file uploading function with the help of yii\web\uploadedfile, models and yii\widgets\activeform.
create a directory ‘uploads’ in the root folder. this directory will hold all of the uploaded images. to upload a single file, you need to create a model and an attribute of the model for uploaded file instance. you should also validate the file upload.
step 1 − inside the models folder, create a file called uploadimageform.php with the following content.
<?php
   namespace app\models;
   use yii\base\model;
   class uploadimageform extends model {
      public $image;
      public function rules() {
         return [
            [['image'], 'file', 'skiponempty' => false, 'extensions' => 'jpg, png'],
         ];
      }
      public function upload() {
         if ($this->validate()) {
            $this->image->saveas('../uploads/' . $this->image->basename . '.' .
               $this->image->extension);
            return true;
         } else {
            return false;
         }
      }
   }
?>
the image attribute is used to keep the file instance. the file validation rule ensures that a file has a png or a jpg extension. the upload function validates the file and saves it on the server.
step 2 − now, add the actionuploadimage function to the sitecontroller.
public function actionuploadimage() {
   $model = new uploadimageform();
   if (yii::$app->request->ispost) {
      $model->image = uploadedfile::getinstance($model, 'image');
      if ($model->upload()) {
         // file is uploaded successfully
         echo "file successfully uploaded";
         return;
      }
   }
   return $this->render('upload', ['model' => $model]);
}
step 3 − when the form is submitted, we call the yii\web\uploadedfile::getinstance() function to represent the uploaded file as an uploadedfile instance. then, we validate the file and save it on the server.
step 4 − next, create an upload.php view file inside the views/site directory.
<?php use yii\widgets\activeform; ?> <?php $form = activeform::begin(['options' => ['enctype' => 'multipart/form-data']])?> <?= $form->field($model, 'image')->fileinput() ?> <button>submit</button> <?php activeform::end() ?>
remember to add the enctype option when you upload a file. the fileinput() method renders the following html code −
<input type = "file">
the above html code allows the users to select and upload files.
step 5 − now, if you go to http://localhost:8080/index.php?r=site/upload-image, you will see the following.
step 6 − select an image to upload and click the “submit” button. the file will be saved on the server inside the ‘uploads’ folder.