How to Upload file in yii 2 framework

To upload files in our yii 2 framework website

we’ll be adding to our module is a file manager with file upload capabilities. For this component, we’ll be creating a dedicated controller to view all of our uploaded files in paginated format, several new classes to handle the actual file upload, and a few view changes to our content save view so that we can associate files with a particular article.

Rather than bundling all of this functionality into our FileController that we’ll be building, we’ll start by building three different components to handle the various aspects of uploading a file. The first class File will represent a $_FILES['file'] object and will provide the functionality for saving the file. The second class, FileUpload, will be our call point for uploading our file and will return the appropriate database to us. The final class, FileUploader, will handle the interactions between the File and FileUpload class. These three classes will ensure that our FileController class is clean and will make working with the file upload extremely easy.

Creating the File class

We’ll start by creating the File class, a simple object that represents $_FILES['file'], that we’ll be sending via a POST request. Create the File.php file in protected/modules/dashboard/components/:

<?php

class File {
    public function save($path)
    {
        if (!move_uploaded_file($_FILES['file']['tmp_name'], $path))
            return false;

        return true;
    }

    public function __get($name)
    {
        if (isset($_FILES['file'][$name]))
            return $_FILES['file'][$name];

        return NULL;
    }
}

For simplicity, we’ll be storing all of our files in the root directory of our main application called /uploads. Go ahead and create this folder now, and make sure that your web server has write access to

 

 

Coming next – Creating the FileUploader class …

About the author

Deven Rathore

I'm Deven Rathore, a multidisciplinary & self-taught designer with 3 years of experience. I'm passionate about technology, music, coffee, traveling and everything visually stimulating. Constantly learning and experiencing new things.

Pin It on Pinterest

Shares