Image upload handle in controller or model

Hi Everyone,

I need to handle upload images for my application that I’m working on and would like to know where is the best practise to handle the uploaded images?

I currently have everything in the controller. So in my controller I would check for the uploaded file, resize it and then save it to a location. Having all that handling in the controller.

Should I make the controller thinner and put the handling to the model?


Uploading file - do like this:

  1. In your model "MyModel" implement property e.g. "uploadFile"

    You must define also rules e.g. like this:

public function rules(){


   array('uploadFile', 'file', 'types'=>'jpg, gif, png', 'allowEmpty' => true),

   array('uploadFile', 'checkUploadNotEmpty'),


add validation method in "MyModel":

public function checkUploadNotEmpty($attr){

        // create object instance for uploaded file, if any

	$this->uploadFile = CUploadedFile::getInstance($this,'uploadFile');


		$this->addError($attr, Yii::t('main', 'Select image file to upload.'));

		return false;


	return true;


  1. in your Controller - just standard validation:

public function actionCreate(){

	$model=new MyModel;




                    // calling validate() will also set model attribute "uploadFile"

		    .. your code ...









Hi Lubos, thanks for your reply.

I already know how to validate the images using the model as you have mentioned above.

I actually wanted to know where should the saving of the image function be located. Is it the controller’s job or the model’s job? or have the controller to call another class to manage it?


hi, I think the saving of the image has to be located at the controller - there you also save the rest of the model.

I prefer to put all image manipulations into a model (usually it is afterSave() method). I think if a model (ActiveRecord) can have an image, then all operations must go into this model. Also I create methods like getImageUrl and getImagePath when storing images in a directory (only a model knows which directory), and in a database - only image names. I only doubt if it is a "true" way to call CUploadedFile::getInstance() inside a model, because it is uses $_FILES array (and using $_POST or $_GET inside models is ugly), but since a model have a property to store CUploadedFile instance, then I think it is ok. Also I use action classes and it is not very handy to put such operations inside them.