hello guys now i am going to show you how to Reuse File Upload Code across multiple projects.

for to reuse this code now am going to create new Behavior called UploadBehavior under components directory that extends CActiveRecordBehavior this is because our Behavior work on events such as beforeSave() and beforeValidate().

classUploadBehaviorextendsCActiveRecordBehavior{}

now create two public properties called $field and $paths one for attribute that accepts file uploads and another for path to save the uploaded file.

/**
* name of the file field that this behavior manages
*/public$field = 'file';
/**
* name of the path where uploaded files are saved
* Note: path must not end with slash ( / )
*/public$path = 'assets';

now create beforeValidate() function that assigns uploaded file to the $field as

now it is time for Action. attach this behavior to your model like this:

for this example you can use Post model of Blog demo. in real time it can be any of your model that allows file uploads.

// Post.phppublicfunctionbehaviors(){returnarray('upload'=>array(// set class name'class'=>'UploadBehavior',
// name of the attribute that receives file upload'field'=>'image',
// name of the path to save uploaded file'path'=>'images', //Note: trailing slash(/) is not required. here we save our file into images));
}

that's all. from now we can reuse this behavior across multiple projects without rewriting the similar code for every file upload.

Note: the above example shows you how to manage single file upload only. you can slightly rewrite the above behavior to accept multiple file uploads.

Extending this Behavior: this behavior can be further extended such as uploading file with unique file name, delete previous file when new file is uploaded, delete the uploaded file when parent record is deleted.