Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • File upload in Yii 2

    • 1
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 3.94k
    Comment on it

    File uploading is one of the most required feature in most of applications. This tutorial demonstrate how we can upload an image file in an application developed on Yii2 framework. There is an inbuilt class yii\web\UploadedFile in Yii2 which can be used for uploading of files. This class encapsulates each uploaded file as an UploadedFile object.

     

    Below are the steps for implementing file upload functionality :

     

    Step 1 : Create a Model class Test.php  inside models directory /models/Test.php .
     

    <?php
    namespace app\models;
    
    use yii\base\Model;
    use yii\web\UploadedFile;
    
    class Test extends Model
    {
        /**
         * instance of UploadedFile
         */
        public $image;
        
        /**
         * define rules for uploading image
         */            
        public function rules()
        {
            return [
                [['image'], 'file', 'skipOnEmpty' => false, 'extensions' => 'png, jpg', 'maxSize' => 1024*1024*2],
            ];
        }
        
    
        /**
         * Function to upload image into /web/uploads directory
         */
        public function upload()
        {
            if ($this->validate()) {
                $this->image->saveAs('uploads/' . $this->image->baseName . '.' . $this->image->extension);
            return $this->image->name;
            } else {
                return false;
            }
        }
    }
    ?>

     

    In the above code, the image attribute is used to keep the instance of UploadedFile. To define the validation rules on uploading image we have used FileValidator, which ensure that only png or jpg images are uploaded. The validation is performed in upload() function, After validating, file saved on the server.


    Currently file validator check only file extensions and maxSize (which is less than 2 MB) properties, There are many other properties which can define as validation rules for uploading files. To define more specific validations for image file you can also use image validator. To use image validator use these rules inside rules().

    [['image'], 'image', 'extensions' => 'png, jpg','minWidth' => 100, 'maxWidth' => 1000, 'minHeight' => 100, 'maxHeight' => 1000,]

     

    For more details about built-in validators provided by Yii, please refer to the Core Validators section.

     

    Step 2 : Create a view file test.php in views directory /views/test/test.php.

    <?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() ?>

     

    fileInput() function will render a <input type="file"> tag.

    Note : Add ['options' => ['enctype' => 'multipart/form-data']] on ActiveForm::begin() method to define enctype.

     

    Step 3 : Create a controller file TestController.php in controllers directory /controllers/TestController.php

     

    <?php
    
    namespace app\controllers;
    
    use Yii;
    use yii\web\Controller;
    use app\models\Test;
    use yii\web\UploadedFile;
    
    class TestController extends Controller
    {
        public function actionTest()
        {
            $model = new Test();
    
            if (Yii::$app->request->isPost) {
                $model->image = UploadedFile::getInstance($model, 'imageFile');
                $image_name = $model->upload();
                if ($image_name) {
                    echo $image." is uploaded successfully";die;
                }
            }
    
            return $this->render('test', ['model' => $model]);
        }
    }
    
    ?>

     

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: