Unique Image Upload Not Working

Hello,

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:

Model




public $image;

...

rules(

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

)

...



Controller




public function actionEdit()

	{

		$model = $this->loadUser();

		$profile=$model->profile;

		

		// ajax validator

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

		{

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

			Yii::app()->end();

		}

		

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

		{

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

			$profile->attributes=$_POST['Profile'];

			$model->image=CUploadedFile::getInstance($model,'image');

			

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

				$model->save();

				$profile->save();

				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."));

				$this->redirect(array('/user/profile'));

			} else $profile->validate();

		}


		$this->render('edit',array(

			'model'=>$model,

			'profile'=>$profile,

		));

	}



View




	<?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:


 $model->image=CUploadedFile::getInstance($model,'image');

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.