Wich are the beneffits of upload a file using a model?

Hi!, I’m writing a code for upload a file and saving extra data to the database.

I read the wiki http://www.yiiframework.com/wiki/2/ but I don’t understand wich are the benefits using this technique. I mean using a “public $image;” for example.

Thanks a lot!

There are no performance benefits but CUploadedFile offers quite a few convenience functions to make your life easier. Ex: saveAs, fileType, extension, etc.



Thanks Matt, this is the only way to use CUploadedFile?

And another question, can I do the upload task via AJAX with CUploadedFile?

Sorry for my english.

The main reason to use it is that you can validate type, max size, etc.

Just like you can validate date, email, integer, string in your models.

Can I know if a upload process was interrupted? I imagine if the upload wasn’t finish, the database will not updated.

The saveAs method returns a boolean indicating if the upload was successful.

    public function actionUpload()


        $model = new Upload;

        if (isset($_POST['Upload']))


            $model->attributes = $_POST['Upload'];

            if ($model->validate())


                $upload = CUploadedFile::getInstance($model, 'file');

                if ($upload->saveAs($filePath))


                    $model->file = $upload->getName(); // Saves the filename to the model's file property