file upload problem

My Docs Controller file




<?php


class DocsController extends Controller

{

	/**

	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning

	 * using two-column layout. See 'protected/views/layouts/column2.php'.

	 */

	public $layout='//layouts/column2';


	/**

	 * @var CActiveRecord the currently loaded data model instance.

	 */

	private $_model;


	/**

	 * @return array action filters

	 */

	public function filters()

	{

		return array(

			'accessControl', // perform access control for CRUD operations

		);

	}


	/**

	 * Specifies the access control rules.

	 * This method is used by the 'accessControl' filter.

	 * @return array access control rules

	 */

	public function accessRules()

	{

		return array(

			array('allow',  // allow all users to perform 'index' and 'view' actions

				'actions'=>array('index','view'),

				'users'=>array('*'),

			),

			array('allow', // allow authenticated user to perform 'create' and 'update' actions

				'actions'=>array('create','update'),

				'users'=>array('@'),

			),

			array('allow', // allow admin user to perform 'admin' and 'delete' actions

				'actions'=>array('admin','delete'),

				'users'=>array('admin'),

			),

			array('deny',  // deny all users

				'users'=>array('*'),

			),

		);

	}


	/**

	 * Displays a particular model.

	 */

	public function actionView()

	{

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

			'model'=>$this->loadModel(),

		));

	}


	/**

	 * Creates a new model.

	 * If creation is successful, the browser will be redirected to the 'view' page.

	 */

	public function actionCreate()

	{

		$model=new Docs;


		// Uncomment the following line if AJAX validation is needed

		// $this->performAjaxValidation($model);


		

		

		

		

		

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

		{

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

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

			if($model->save())

				//$model->filename->saveAs('../../pics/.jpg');


				$this->redirect(array('view','id'=>$model->docsid));

				 $model->filename->saveAs('/tmp/uploads/');

		}


		$this->render('create',array('model'=>$model));

	

	


	

	}


	/**

	 * Updates a particular model.

	 * If update is successful, the browser will be redirected to the 'view' page.

	 */

	public function actionUpdate()

	{

		$model=$this->loadModel();


		// Uncomment the following line if AJAX validation is needed

		// $this->performAjaxValidation($model);


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

		{

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

			if($model->save())

				$this->redirect(array('view','id'=>$model->docsid));

		}


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

			'model'=>$model,

		));

	}


	/**

	 * Deletes a particular model.

	 * If deletion is successful, the browser will be redirected to the 'index' page.

	 */

	public function actionDelete()

	{

		if(Yii::app()->request->isPostRequest)

		{

			// we only allow deletion via POST request

			$this->loadModel()->delete();


			// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser

			if(!isset($_GET['ajax']))

				$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));

		}

		else

			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');

	}


	/**

	 * Lists all models.

	 */

	public function actionIndex()

	{

		$dataProvider=new CActiveDataProvider('Docs');

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

			'dataProvider'=>$dataProvider,

		));

	}


	/**

	 * Manages all models.

	 */

	public function actionAdmin()

	{

		$model=new Docs('search');

		$model->unsetAttributes();  // clear any default values

		if(isset($_GET['Docs']))

			$model->attributes=$_GET['Docs'];


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

			'model'=>$model,

		));

	}


	/**

	 * Returns the data model based on the primary key given in the GET variable.

	 * If the data model is not found, an HTTP exception will be raised.

	 */

	public function loadModel()

	{

		if($this->_model===null)

		{

			if(isset($_GET['id']))

				$this->_model=Docs::model()->findByPk($_GET['id']);

			if($this->_model===null)

				throw new CHttpException(404,'The requested page does not exist.');

		}

		return $this->_model;

	}


	/**

	 * Performs the AJAX validation.

	 * @param CModel the model to be validated

	 */

	protected function performAjaxValidation($model)

	{

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

		{

			echo CActiveForm::validate($model);

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

		}

	}

}






My Model file Docs.php




<?php


/**

 * This is the model class for table "{{docs}}".

 *

 * The followings are the available columns in table '{{docs}}':

 * @property string $document_name

 * @property string $document_author

 * @property string $document_title

 * @property string $document_desc

 * @property integer $docsid

 */

class Docs extends CActiveRecord

{


	public $image;	


	/**

	 * Returns the static model of the specified AR class.

	 * @return Docs the static model class

	 */

	public static function model($className=__CLASS__)

	{

		return parent::model($className);

	}


	/**

	 * @return string the associated database table name

	 */

	public function tableName()

	{

		return '{{docs}}';

	}


	/**

	 * @return array validation rules for model attributes.

	 */

	public function rules()

	{

		// NOTE: you should only define rules for those attributes that

		// will receive user inputs.

		return array(

			array('document_name, document_author, document_title, document_desc', 'required'),

			array('document_name, document_author, document_title, document_desc', 'length', 'max'=>255),

			array('image', 'file', 'types'=>'jpg,jpeg,gif,png', 'maxSize'=>30720),

      		array('image', 'required'),


			

			

			

			

			// The following rule is used by search().

			// Please remove those attributes that should not be searched.

			array('document_name, document_author, document_title, document_desc, docsid', 'safe', 'on'=>'search'),

		);

	}


	/**

	 * @return array relational rules.

	 */

	public function relations()

	{

		// NOTE: you may need to adjust the relation name and the related

		// class name for the relations automatically generated below.

		return array(

		);

	}


	/**

	 * @return array customized attribute labels (name=>label)

	 */

	public function attributeLabels()

	{

		return array(

			'document_name' => 'Document Name',

			'document_author' => 'Document Author',

			'document_title' => 'Document Title',

			'document_desc' => 'Document Desc',

			'docsid' => 'Docsid',

		);

	}


	/**

	 * Retrieves a list of models based on the current search/filter conditions.

	 * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.

	 */

	public function search()

	{

		// Warning: Please modify the following code to remove attributes that

		// should not be searched.


		$criteria=new CDbCriteria;


		$criteria->compare('document_name',$this->document_name,true);


		$criteria->compare('document_author',$this->document_author,true);


		$criteria->compare('document_title',$this->document_title,true);


		$criteria->compare('document_desc',$this->document_desc,true);


		$criteria->compare('docsid',$this->docsid);


		return new CActiveDataProvider(get_class($this), array(

			'criteria'=>$criteria,

		));

	}

}




My site view file docs/_form.php




<div class="form">


<?php $form=$this->beginWidget('CActiveForm', array(

	'id'=>'docs-form',

	'enableAjaxValidation'=>false,

)); ?>


	<p class="note">Fields with <span class="required">*</span> are required.</p>


	<?php echo $form->errorSummary($model); ?>


	<div class="row">

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

		<?php echo $form->textField($model,'document_name',array('size'=>60,'maxlength'=>255)); ?>

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

	</div>


	<div class="row">

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

		<?php echo $form->textField($model,'document_author',array('size'=>60,'maxlength'=>255)); ?>

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

	</div>


	<div class="row">

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

		<?php echo $form->textField($model,'document_title',array('size'=>60,'maxlength'=>255)); ?>

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

	</div>


	<div class="row">

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

		<?php echo $form->textField($model,'document_desc',array('size'=>60,'maxlength'=>255)); ?>

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

	</div>


	<div class="row">

		 <?php echo CHtml::form('','post',array('enctype'=>'multipart/form-data')); ?>


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

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

		<?php echo CHtml::submitButton('UPLOAD'); ?>




	</div>













	<div class="row buttons">

		<?php echo CHtml::submitButton($model->isNewRecord ? 'Create' : 'Save'); ?>

	</div>


<?php $this->endWidget(); ?>


</div><!-- form -->



i m getting following error

CException

Description

Property "Docs.filename" is not defined.

In advance thank you for your help guys. YII rocksss

This is a copy of your code




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

if($model->save())

       //$model->filename->saveAs('../../pics/.jpg');


       $this->redirect(array('view','id'=>$model->docsid));

	   $model->filename->saveAs('/tmp/uploads/');



So first you use $model->image and then you change to $model->filename…

Use $model->image->saveAs(…)… and put it before the redirect…

now if i change according to your post

i get following error.




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

		{

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

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

			$model->image->saveAs('/tmp/uploads/');

			

				//echo $model->image->name;

			if($model->save())

				$this->redirect(array('view','id'=>$model->docsid));

				 //$model->attributes->saveAs('/tmp/uploads/');

		}


		$this->render('create',array('model'=>$model));

	



Fatal error: Call to a member function saveAs() on a non-object in C:\wamp\www\docmg\protected\controllers\DocsController.php on line 82…

method2.

And if i modify code as follows…




	

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

		{

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

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

			//$model->image->saveAs('/tmp/uploads/');

			

				//echo $model->image->name;

			if($model->save())

			    $model->image->saveAs('/tmp/uploads/');

				$this->redirect(array('view','id'=>$model->docsid));

				 //$model->attributes->saveAs('/tmp/uploads/');

		}


		$this->render('create',array('model'=>$model));



i get this error with image not got uploaded…

Error 404.

The requested page does not exist.

First of all you should read the documentation carefully… - http://www.yiiframew…Instance-detail

As it says getinstance can return null if no file has been uploaded… in that case you cannot use saveAs() so you get the first error…

for saveAs() you have to specify the file name not only the path

Edit:

check this cookbook for more info - http://www.yiiframework.com/doc/cookbook/2/


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

		{

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

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

			//$model->image1 = CUploadedFile::getName();

			

			//$model->image->saveAs('/tmp/image1.jpg',true);			

				//echo $model->image->name;

			if($model->save())

			   

			   $model->image->saveAs('/tmp/.jpg',$deleteTempFile=false);

			   

				$this->redirect(array('view','id'=>$model->docsid));

				 //$model->attributes->saveAs('/tmp/uploads/');

		}


		$this->render('create',array('model'=>$model));



dude now i qrote this code…bt still its giving 404 error and tmp folder is also empty…

can u please suggest me proper code…or and complete working example…as i m new to yii…

The cookbook is OK…

In your example you did not give a filename to the image you want to save… "/tmp/.jpg" is not a filename !!!

check that the web process has a write permission for that folder…

and after model save you probably want to put image save and redirect inside the curly braces { }

hey dude i get this error

CException

Description

Property "DocsController._name" is not defined.




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

		{

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

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

			//$model->image1 = CUploadedFile::getName();

			$model->image = CUploadedFile::getName();

			

			//$model->image->saveAs('/tmp/image1.jpg',true);			

				//echo $model->image->name;

			if($model->save())

			   

			   

			  // $model->image->saveAs('.jpg',$deleteTempFile=true);

				$this->redirect(array('view','id'=>$model->docsid));

			    //$model->attributes->saveAs('/tmp/uploads/');

		}


				

		$this->render('create',array('model'=>$model));

	

	


	

	}




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

$model->image->saveAs($model->image->name);

See if the above code works…[not tested]

betor i tried your method also…but its not uploading images.

i am not able to get even image name using


$model->image1 = CUploadedFile::getName();

guys is there any way i can know whether image is getting upload or not.

thanks for help guys.

After


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

$model->image is NULL or an instance of the uploaded file - http://www.yiiframework.com/doc/api/CUploadedFile#getInstance-detail

So check first if it’s null…

The name you can get with $model->image->name

Hi,

You should specify the image folder location in


$model->image->saveAs('images/'.$model->image->name);

This works for me…

Try this code:


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

                {

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

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

      

                        $model->image->saveAs('tmp/'.$model->image->name);                        

  

                        if($model->save())

                                $this->redirect(array('view','id'=>$model->docsid));

        

                }              

                $this->render('create',array('model'=>$model));

        }

your image should be uploaded in your tmp folder.