Unique Image Upload Not Working


I am having trouble saving a record to my database. In particular, when I upload an image I want to add md5(rand(0,1000)) as a prefix to the image in order to uniquely identify it. When I save the record the image saves correctly to the web folder but in my MySQL database it does not have the md5 hash as a prefix. For example if I were to upload a file named picture.jpg, it would show up as n2b1672a54b7954e8a69c9f219picture.jpg in my web folder but in my database it would just be picture.jpg. I am really at a loss as to what this could be. I have tried hundreds of different combinations but I cannot get it to save properly. Here is my code:


public $image;



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




public function actionEdit()


		$model = $this->loadUser();



		// ajax validator

		if(isset($_POST['ajax']) && $_POST['ajax']==='profile-form')


			echo UActiveForm::validate(array($model,$profile));










			if($model->validate() && $profile->validate()) {



				if(is_object($model->image) && $model->save())


					$model->image->saveAs(Yii::app()->basePath . '/../images/' . $model->encrypt(rand(0,1000)) . $model->image);


				Yii::app()->user->setFlash('profileMessage',UserModule::t("Changes have been saved."));


			} else $profile->validate();








	<?php echo $form->labelEx($model,'image'); ?>

	<?php echo CHtml::activeFileField($model, 'image'); ?>

	<?php echo $form->error($model,'image'); ?>

I have enctype’=>'multipart/form-data in my view as well. Also just to note I am using the yii-user module and I am trying to successfully add image upload to it but it is obviously not working properly. Any help would be appreciated.

You probably need to save the uploaded file first under the new name, before assigning it to your models field. :)

Sorry, I am still kind of new to this. Would you be able to explain please? How would I be able to save it prior to saving the active record? Thank you.

After this line:


Set the $model->name (whatever you are using for the name attribute) to the hashed name. Use that later in your saveAs call.

You need to set the model name prior to the save() call.