Xupload Error

I have done like what they have told in xupload workflow…

Controller:




public function actionForm( )

    {

        $hiflashFilemodel = new HiflashFile;

        Yii::import("ext.xupload.models.XUploadForm");

        $model = new XUploadForm;

        //Check if the form has been submitted

        if (isset($_POST['XUploadForm'])) {

            //Assign our safe attributes

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

            //Start a transaction in case something goes wrong

            $transaction = Yii::app()->db->beginTransaction();

            try {

                //Save the model to the database

                if ($model->save()) {

                    $transaction->commit();

                }

            } catch (Exception $e) {

                $transaction->rollback();

                Yii::app()->handleException($e);

            }

        }

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

            'model' => $model,

            'hiflashFilemodel' => $hiflashFilemodel,

        ));

    }

    

    public function actionUpload( )

    {

        Yii::import( "xupload.models.XUploadForm" );

        //Here we define the paths where the files will be stored temporarily

        $path = realpath( Yii::app( )->getBasePath( )."/uploads/" )."/";

        $publicPath = Yii::app( )->getBasePath( )."/uploads/";

        

        //This is for IE which doens't handle 'Content-type: application/json' correctly

        header( 'Vary: Accept' );

        if( isset( $_SERVER['HTTP_ACCEPT'] ) && (strpos( $_SERVER['HTTP_ACCEPT'], 'application/json' ) !== false) )

        {

            header( 'Content-type: application/json' );

        }

        else

        {

            header( 'Content-type: text/plain' );

        }

     

        //Here we check if we are deleting and uploaded file

        if( isset( $_GET["_method"] ) )

        {

            if( $_GET["_method"] == "delete" )

            {

                if( $_GET["file"][0] !== '.' )

                {

                    $file = $path.$_GET["file"];

                    if( is_file( $file ) )

                    {

                        unlink( $file );

                    }

                }

                echo json_encode( true );

            }

        }

        else

        {

            $model = new XUploadForm;

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

            

            //We check that the file was successfully uploaded

            if( $model->file !== null )

            {

                //Grab some data

                $model->mime_type = $model->file->getType( );

                $model->size = $model->file->getSize( );

                $model->name = $model->file->getName( );

                //(optional) Generate a random name for our file

                $filename = md5( Yii::app( )->user->id.microtime( ).$model->name);

                $filename .= ".".$model->file->getExtensionName( );

                if( $model->validate( ) )

                {

                    //Move our file to our temporary dir

                    $model->file->saveAs( $path.$filename );

                    chmod( $path.$filename, 0777 );

                    //here you can also generate the image versions you need 

                    //using something like PHPThumb

     

     

                    //Now we need to save this path to the user's session

                    if( Yii::app( )->user->hasState('hiflash_file') )

                    {

                        $userFiles = Yii::app( )->user->getState('hiflash_file');

                        //var_dump($userImages);

                    } else {

                        $userFiles = array();

                        //var_dump($userImages);

                    }

                     $userFiles[] = array(

                        "path" => $path.$filename,

                        //the same file or a thumb version that you generated

                        "thumb" => $path.$filename,

                        "filename" => $filename,

                        'size' => $model->size,

                        'mime' => $model->mime_type,

                        'name' => $model->name,

                    );

                    Yii::app( )->user->setState('hiflash_file', $userFiles);

     

                    //Now we need to tell our widget that the upload was succesfull

                    //We do so, using the json structure defined in

                    // https://github.com/blueimp/jQuery-File-Upload/wiki/Setup

                    echo json_encode( array( array(

                            "name" => $model->name,

                            "type" => $model->mime_type,

                            "size" => $model->size,

                            "url" => $publicPath.$filename,

                            "thumbnail_url" => $publicPath.$filename,

                            "delete_url" => $this->createUrl( "upload", array(

                                "_method" => "delete",

                                "file" => $filename

                            ) ),

                            "delete_type" => "POST"

                        ) ) );

                }

                else

                {

                    //If the upload failed for some reason we log some data and let the widget know

                    echo json_encode( array( 

                        array( "error" => $model->getErrors( 'file' ),

                    ) ) );

                    Yii::log( "XUploadAction: ".CVarDumper::dumpAsString( $model->getErrors( ) ),

                        CLogger::LEVEL_ERROR, "ext.xupload.actions.XUploadAction" 

                    );

                }

            }

            else

            {

                throw new CHttpException( 500, "Could not upload file" );

            }

        }

    }



Model:

HiflashFile:




public function afterSave()

    {

        $this->addFiles();

        parent::afterSave();

    }


    public function addFiles()

    {

        //If we have pending images

        if (Yii::app()->user->hasState('hiflash_file'))

        {

            $userFiles = Yii::app()->user->getState('hiflash_file');

            //Resolve the final path for our images

            $path = Yii::app()->getBasePath() . "/uploads/{$this->id}/";

            //Create the folder and give permissions if it doesnt exists

            if (!is_dir($path))

            {

                mkdir($path);

                chmod($path, 0777);

            }

            //Now lets create the corresponding models and move the files

            foreach ($userFiles as $files)

            {

                if (is_file($files["path"]))

                {

                    if (rename($files["path"], $path . $files["filename"])) {

                        chmod($path . $files["filename"], 0777);

                        $fi = new uploadForm();

                        var_dump($img);

                        $fi->size = $files["size"];

                        $fi->mime = $files["mime"];

                        $fi->name = $files["name"];

                        $fi->source = "/uploads/{$this->id}/" . $files["filename"];

                        $fi->XUploadForm_id = $this->id;

                        if (!$fi->save()) {

                            //Its always good to log something

                            Yii::log("Could not save File:\n" . CVarDumper::dumpAsString(

                                            $fi->getErrors()), CLogger::LEVEL_ERROR);

                            //this exception will rollback the transaction

                            throw new Exception('Could not save File');

                        }

                    }

                } else {

                    //You can also throw an execption here to rollback the transaction

                    Yii::log($files["path"] . " is not a file", CLogger::LEVEL_WARNING);

                }

            }

            //Clear the user's session

            Yii::app()->user->setState('hiflash_file', null);

        }

    }



uploadForm Model:




<?php


class XUploadForm extends CFormModel


{


        public $file;


        public $mime_type;


        public $size;


        public $name;


        public $filename;





        /**


         * @var boolean dictates whether to use sha1 to hash the file names


         * along with time and the user id to make it much harder for malicious users


         * to attempt to delete another user's file


        */


        public $secureFileNames = false;





        /**


         * Declares the validation rules.


         * The rules state that username and password are required,


         * and password needs to be authenticated.


         */


        public function rules()


        {


                return array(


                        array('file', 'file'),


                );


        }





        /**


         * Declares attribute labels.


         */


        public function attributeLabels()


        {


                return array(


                        'file'=>'Upload files',


                );


        }





        public function getReadableFileSize($retstring = null) {


                // adapted from code at http://aidanlister.com/repos/v/function.size_readable.php


                $sizes = array('bytes', 'kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB');





                if ($retstring === null) { $retstring = '%01.2f %s'; }





                $lastsizestring = end($sizes);





                foreach ($sizes as $sizestring) {


                        if ($this->size < 1024) { break; }


                        if ($sizestring != $lastsizestring) { $this->size /= 1024; }


                }


                if ($sizestring == $sizes[0]) { $retstring = '%01d %s'; } // Bytes aren't normally fractional


                return sprintf($retstring, $this->size, $sizestring);


        }





        /**


         * A stub to allow overrides of thumbnails returned


         * @since 0.5


         * @author acorncom


         * @return string thumbnail name (if blank, thumbnail won't display)


         */


        public function getThumbnailUrl($publicPath) {


            return $publicPath.$this->filename;


        }





        /**


         * Change our filename to match our own naming convention


        * @return bool


        */


        public function beforeValidate() {





            //(optional) Generate a random name for our file to work on preventing


            // malicious users from determining / deleting other users' files


            if($this->secureFileNames)


            {


                $this->filename = sha1( Yii::app( )->user->id.microtime( ).$this->name);


                $this->filename .= ".".$this->file->getExtensionName( );


            }





            return parent::beforeValidate();


        }


}






Views:

_form:




<?php

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

          'id' => 'hiflash-file-form',

          'enableAjaxValidation' => false,

            //This is very important when uploading files

          'htmlOptions' => array('enctype' => 'multipart/form-data'),

        ));

      ?>    

      <h1 style="text-align: center; text-transform: uppercase;">Upload Files</h1>

        <div class="row">

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

            <?php //echo $form->textField($model,'quotation_id'); ?>

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

        </div>

        <!-- Other Fields... -->

        <div class="form-row">

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

            <?php

            $this->widget( 'xupload.XUpload', array(

                'url' => Yii::app( )->createUrl( "/HiflashFile/upload"),

                //our XUploadForm

                'model' => $model,

                //We set this for the widget to be able to target our own form

                'htmlOptions' => array('id'=>'hiflash-file-form'),

                'attribute' => 'file',

                'multiple' => true,

                //Note that we are using a custom view for our widget

                //Thats becase the default widget includes the 'form' 

                //which we don't want here

                'formView' => 'application.views.hiflashFile._form1',

                )    

            );

            ?>



_form1:




<!-- The file upload form used as target for the file upload widget -->





<div class="row fileupload-buttonbar">


	<div class="span7">


		<!-- The fileinput-button span is used to style the file input field as button -->


		<span class="btn btn-success fileinput-button">


            <i class="icon-plus icon-white"></i>


            <span><?php echo $this->t('1#Add files|0#Choose file', $this->multiple); ?></span>


			<?php


            if ($this -> hasModel()) :


                echo CHtml::activeFileField($this -> model, $this -> attribute, $htmlOptions) . "\n";


            else :


                echo CHtml::fileField($name, $this -> value, $htmlOptions) . "\n";


            endif;


            ?>


		</span>


        <?php if ($this->multiple) { ?>


		<button type="submit" class="btn btn-primary start">


			<i class="icon-upload icon-white"></i>


			<span>Start upload</span>


		</button>


		<button type="reset" class="btn btn-warning cancel">


			<i class="icon-ban-circle icon-white"></i>


			<span>Cancel upload</span>


		</button>


		<button type="button" class="btn btn-danger delete">


			<i class="icon-trash icon-white"></i>


			<span>Delete</span>


		</button>


		<input type="checkbox" class="toggle">


        <?php } ?>


	</div>


	<div class="span5">


		<!-- The global progress bar -->


		<div class="progress progress-success progress-striped active fade">


			<div class="bar" style="width:0%;"></div>


		</div>


	</div>


</div>


<!-- The loading indicator is shown during image processing -->


<div class="fileupload-loading"></div>


<br>


<!-- The table listing the files available for upload/download -->


<table class="table table-striped">


	<tbody class="files" data-toggle="modal-gallery" data-target="#modal-gallery"></tbody>


</table>






I have attached my file which shows me a error. can any one help me with this? and what mistake have i done here?

Thanks in Advance :)