[Extension] Xupload

here is the html code generated.

Thanks again

Not sure what is happening, couldn’t tell with out taking a deeper look, and I don’t have much time currently I’m moving away so I may even be without internet for a while too.

ok! no problem… thanks!

I tried everything but I always get 500 Internal Server Error when I click upload.

Controller (controllers/ArquivoController)




class ArquivoController extends GxController {


////////////XUPLOAD///////////


	public function actions() {

		return array('upload' => array('class' => 'xupload.actions.XUploadAction', 'path' => Yii::app() -> getBasePath() . "/../images/uploads", "publicPath" => Yii::app()->getBaseUrl()."/images/uploads" ), );

	}


////////////XUPLOAD///////////

	

	public function actionCreate() {

	$model = new Arquivo;

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

    //$photos = new XUploadForm;

    //Check if the form has been submitted

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

        //Assign our safe attributes

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

        //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( '_form', array(

        'model' => $model,

        'photos' => $photos,

    ));

	}

	

	////////////XUPLOAD///////////

	

	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( )."/../images/uploads/tmp/" )."/";

    $publicPath = Yii::app( )->getBaseUrl( )."/images/uploads/tmp/";

 

    //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( 'images' ) ) {

                    $userImages = Yii::app( )->user->getState( 'images' );

                } else {

                    $userImages = array();

                }

                 $userImages[] = 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( 'images', $userImages );

 

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

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

                echo json_encode( array( array(

                        "name" => $model->name,

                        "type" => $model->mime_type,

                        "size" => $model->size,

                        "url" => $publicPath.$filename,

                        "thumbnail_url" => $publicPath."thumbs/$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, "xupload.actions.XUploadAction" 

                );

            }

        } else {

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

        }

    }}

	}



Form View (views/arquivo/_form)




<div class="form">




<?php $form = $this->beginWidget('bootstrap.widgets.TbActiveForm', array(

	'id' => 'arquivo-form',

	'enableAjaxValidation' => false,

));

?>


	<p class="note">

		<?php echo Yii::t('app', 'Fields with'); ?> <span class="required">*</span> <?php echo Yii::t('app', 'are required'); ?>.

	</p>


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


		<div class="row">

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

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

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

		</div><!-- row -->

		<div class="row">

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

		<?php echo $form->dropDownList($model, 'categoria_id', GxHtml::listDataEx(Categoria::model()->findAllAttributes(null, true))); ?>

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

		</div><!-- row -->

		<div class="row">

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

		<?php echo $form->dropDownList($model, 'usuario_id', GxHtml::listDataEx(Usuario::model()->findAllAttributes(null, true))); ?>

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

		</div><!-- row -->

		<div class="row">

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

            <?php

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

                'url' => Yii::app( )->createUrl( "/arquivo/upload", array('id'=>$model->id)),

                //our XUploadForm

                'model' => $model,

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

                'htmlOptions' => array('id'=>'arquivo-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.arquivo._upload',

				

                )    

            );

            ?>

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

        </div>




<div class="form-actions">

		<?php $this->widget('bootstrap.widgets.TbButton', array(

			'buttonType'=>'submit',

			'type'=>'primary',

			'label'=>$model->isNewRecord ? 'Criar' : 'Salvar',

		)); ?>

	</div>


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

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



Upload form (views/arquivo/_upload




<!-- 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>Add files...</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>

		<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">

	</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>



First if you are not ussing the generic upload action you do not need to install it in your controller, so remove this:


public function actions() {

                return array('upload' => array('class' => 'xupload.actions.XUploadAction', 'path' => Yii::app() -> getBasePath() . "/../images/uploads", "publicPath" => Yii::app()->getBaseUrl()."/images/uploads" ), );

        }

Now you have an uploadAction in your controller, that isn’t customized, so it is still looking for an XUploadForm model, but in your actionCreate you are creating an ‘Arquivo’ model, so the if is failing and you are getting the 500: Could not upload file:




        $model = new XUploadForm;

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

        //We check that the file was successfully uploaded

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

                ...

        } else {

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

        }

so change it so that it search for your own model




        $model = new Arquivo;

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

        //We check that the file was successfully uploaded

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

                ...

        } else {

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

        }

Thanks for help!

I did as you told but still getting the error…

The widget




<div class="row">

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

            <?php

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

                'url' => Yii::app( )->createUrl( "/arquivo/upload", array('id'=>$model->id)),

                //our XUploadForm

                'model' => $model,

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

                'htmlOptions' => array('id'=>'arquivo-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.arquivo._upload',

				

                )    

            );

            ?>

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

        </div>



The controller




////////////XUPLOAD///////////

	

	public function actionCreate() {

	$model = new Arquivo;

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

    //Check if the form has been submitted

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

        //Assign our safe attributes

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

        //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( '_form', array(

        'model' => $model,

    ));

	}

	

	////////////XUPLOAD///////////

	

	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( )."/../images/uploads/tmp/" )."/";

    $publicPath = Yii::app( )->getBaseUrl( )."/images/uploads/tmp/";

 

    //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 Arquivo;

        $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( 'images' ) ) {

                    $userImages = Yii::app( )->user->getState( 'images' );

                } else {

                    $userImages = array();

                }

                 $userImages[] = 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( 'images', $userImages );

 

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

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

                echo json_encode( array( array(

                        "name" => $model->name,

                        "type" => $model->mime_type,

                        "size" => $model->size,

                        "url" => $publicPath.$filename,

                        "thumbnail_url" => $publicPath."thumbs/$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, "xupload.actions.XUploadAction" 

                );

            }

        } else {

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

        }

    }}



check that your form has enctype="multipart/form-data"

Yes

The full form code




<div class="form">




<?php $form = $this->beginWidget('bootstrap.widgets.TbActiveForm', array(

	'id' => 'arquivo-form',

	'enableAjaxValidation' => false,

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

));

?>


	<p class="note">

		<?php echo Yii::t('app', 'Fields with'); ?> <span class="required">*</span> <?php echo Yii::t('app', 'are required'); ?>.

	</p>


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


		<div class="row">

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

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

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

		</div><!-- row -->

		<div class="row">

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

		<?php echo $form->dropDownList($model, 'categoria_id', GxHtml::listDataEx(Categoria::model()->findAllAttributes(null, true))); ?>

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

		</div><!-- row -->

		<div class="row">

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

		<?php echo $form->dropDownList($model, 'usuario_id', GxHtml::listDataEx(Usuario::model()->findAllAttributes(null, true))); ?>

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

		</div><!-- row -->

		<div class="row">

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

            <?php

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

                'url' => Yii::app( )->createUrl( "/arquivo/upload", array('id'=>$model->id)),

                //our XUploadForm

                'model' => $model,

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

                'htmlOptions' => array('id'=>'arquivo-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.arquivo._upload',

				

                )    

            );

            ?>

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

        </div>




<div class="form-actions">

		<?php $this->widget('bootstrap.widgets.TbButton', array(

			'buttonType'=>'submit',

			'type'=>'primary',

			'label'=>$model->isNewRecord ? 'Criar' : 'Salvar',

		)); ?>

	</div>


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

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



I don’t known if it is a problem, but I’m using Giix

Check your logs, the extension seems to be configured properly, it might be an issue with uploading files in your server.

PHP, Apache or Yii log?

Most likely apache, since its a 500 server error, then php.

Nothing in Apache and PHP logs…

Trying for one week to fix this error, getting crazy…

The full codes again

///FORM




<div class="form">




<?php $form = $this->beginWidget('bootstrap.widgets.TbActiveForm', array(

	'id' => 'arquivo-form',

	'enableAjaxValidation' => false,

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

));

?>


	<p class="note">

		<?php echo Yii::t('app', 'Fields with'); ?> <span class="required">*</span> <?php echo Yii::t('app', 'are required'); ?>.

	</p>


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


		<div class="row">

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

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

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

		</div><!-- row -->

		<div class="row">

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

		<?php echo $form->dropDownList($model, 'categoria_id', GxHtml::listDataEx(Categoria::model()->findAllAttributes(null, true))); ?>

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

		</div><!-- row -->

		<div class="row">

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

		<?php echo $form->dropDownList($model, 'usuario_id', GxHtml::listDataEx(Usuario::model()->findAllAttributes(null, true))); ?>

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

		</div><!-- row -->

		<div class="row">

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

            <?php

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

                'url' => Yii::app( )->createUrl( "/arquivo/upload", array('id'=>$model->id)),

                //our XUploadForm

                'model' => $model,

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

                'htmlOptions' => array('id'=>'arquivo-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.arquivo._upload',

				

                )    

            );

            ?>

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

        </div>




<div class="form-actions">

		<?php $this->widget('bootstrap.widgets.TbButton', array(

			'buttonType'=>'submit',

			'type'=>'primary',

			'label'=>$model->isNewRecord ? 'Criar' : 'Salvar',

		)); ?>

	</div>


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

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



///UPLOAD FORM




<!-- 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>Add files...</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>

		<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">

	</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>



///CONTROLLER




<?php


class ArquivoController extends GxController {




	

	

	public function actionView($id) {

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

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

		));

	}




	public function actionUpdate($id) {

		$model = $this->loadModel($id, 'Arquivo');




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

			$model->setAttributes($_POST['Arquivo']);


			if ($model->save()) {

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

			}

		}


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

				'model' => $model,

				));

	}


	public function actionDelete($id) {

		if (Yii::app()->getRequest()->getIsPostRequest()) {

			$this->loadModel($id, 'Arquivo')->delete();


			if (!Yii::app()->getRequest()->getIsAjaxRequest())

				$this->redirect(array('admin'));

		} else

			throw new CHttpException(400, Yii::t('app', 'Your request is invalid.'));

	}


	public function actionIndex() {

		$dataProvider = new CActiveDataProvider('Arquivo');

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

			'dataProvider' => $dataProvider,

		));

	}


	public function actionAdmin() {

		$model = new Arquivo('search');

		$model->unsetAttributes();


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

			$model->setAttributes($_GET['Arquivo']);


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

			'model' => $model,

		));

	}

	

	////////////XUPLOAD///////////

	

	public function actionCreate() {

	$model = new Arquivo;

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

    //Check if the form has been submitted

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

        //Assign our safe attributes

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

        //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( 'create', array(

        'model' => $model,

    ));

	}

	

	////////////XUPLOAD///////////

	

	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( )."/../images/uploads/tmp/" )."/";

    $publicPath = Yii::app( )->getBaseUrl( )."/images/uploads/tmp/";

 

    //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 Arquivo;

        $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( 'images' ) ) {

                    $userImages = Yii::app( )->user->getState( 'images' );

                } else {

                    $userImages = array();

                }

                 $userImages[] = 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( 'images', $userImages );

 

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

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

                echo json_encode( array( array(

                        "name" => $model->name,

                        "type" => $model->mime_type,

                        "size" => $model->size,

                        "url" => $publicPath.$filename,

                        "thumbnail_url" => $publicPath."thumbs/$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, "xupload.actions.XUploadAction" 

                );

            }

        } else {

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

        }

    }}

	}



///MODEL




<?php


/**

 * This is the model base class for the table "Arquivo".

 * DO NOT MODIFY THIS FILE! It is automatically generated by giix.

 * If any changes are necessary, you must set or override the required

 * property or method in class "Arquivo".

 *

 * Columns in table "Arquivo" available as properties of the model,

 * followed by relations of table "Arquivo" available as properties of the model.

 *

 * @property string $id

 * @property string $nome

 * @property string $categoria_id

 * @property string $usuario_id

 * @property string $file

 * @property string $photos

 * @property string $arquivo

 * @property string $name

 * @property string $type

 * @property string $size

 * @property string $url

 * @property string $thumbnail_url

 * @property string $delete_url

 *

 * @property Categoria $categoria

 * @property Usuario $usuario

 */

abstract class BaseArquivo extends GxActiveRecord {


	public static function model($className=__CLASS__) {

		return parent::model($className);

	}


	public function tableName() {

		return 'Arquivo';

	}


	public static function label($n = 1) {

		return Yii::t('app', 'Arquivo|Arquivos', $n);

	}


	public static function representingColumn() {

		return 'nome';

	}


	public function rules() {

		return array(

			array('nome, file, photos, arquivo, name, type, size, url, thumbnail_url, delete_url', 'length', 'max'=>255),

			array('categoria_id, usuario_id', 'length', 'max'=>11),

			array('nome, categoria_id, usuario_id, file, photos, arquivo, name, type, size, url, thumbnail_url, delete_url', 'default', 'setOnEmpty' => true, 'value' => null),

			array('id, nome, categoria_id, usuario_id, file, photos, arquivo, name, type, size, url, thumbnail_url, delete_url', 'safe', 'on'=>'search'),

		);

	}


	public function relations() {

		return array(

			'categoria' => array(self::BELONGS_TO, 'Categoria', 'categoria_id'),

			'usuario' => array(self::BELONGS_TO, 'Usuario', 'usuario_id'),

		);

	}


	public function pivotModels() {

		return array(

		);

	}


	public function attributeLabels() {

		return array(

			'id' => Yii::t('app', 'ID'),

			'nome' => Yii::t('app', 'Nome'),

			'categoria_id' => null,

			'usuario_id' => null,

			'file' => Yii::t('app', 'File'),

			'photos' => Yii::t('app', 'Photos'),

			'arquivo' => Yii::t('app', 'Arquivo'),

			'name' => Yii::t('app', 'Name'),

			'type' => Yii::t('app', 'Type'),

			'size' => Yii::t('app', 'Size'),

			'url' => Yii::t('app', 'Url'),

			'thumbnail_url' => Yii::t('app', 'Thumbnail Url'),

			'delete_url' => Yii::t('app', 'Delete Url'),

			'categoria' => null,

			'usuario' => null,

		);

	}

    

    public function behaviors()

	{

    return array('datetimeI18NBehavior' => array('class' => 'ext.DateTimeI18NBehavior')); // 'ext' is in Yii 1.0.8 version. For early versions, use 'application.extensions' instead.

	}


	public function search() {

		$criteria = new CDbCriteria;


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

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

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

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

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

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

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

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

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

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

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

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

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


		return new CActiveDataProvider($this, array(

			'criteria' => $criteria,

		));

	}

	

	

	//in protected/models/SomeModel.php

public function afterSave( ) {

    $this->addImages( );

    parent::afterSave( );

}

 

public function addImages( ) {

    //If we have pending images

    if( Yii::app( )->user->hasState( 'images' ) ) {

        $userImages = Yii::app( )->user->getState( 'images' );

        //Resolve the final path for our images

        $path = Yii::app( )->getBasePath( )."/../images/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( $userImages as $image ) {

            if( is_file( $image["path"] ) ) {

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

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

                    $img = new Image( );

                    $img->size = $image["size"];

                    $img->mime = $image["mime"];

                    $img->name = $image["name"];

                    $img->source = "/images/uploads/{$this->id}/".$image["filename"];

                    $img->arquivo_id = $this->id;

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

                        //Its always good to log something

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

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

                        //this exception will rollback the transaction

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

                    }

                }

            } else {

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

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

            }

        }

        //Clear the user's session

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

    }

}

}



have you tried uploading other files? I mean without using the extension? do you have display_errors and error_reporting in PHP?

Worked when I copied the xupload/model/XUploadForm inside the ‘Arquivo’ model!!

Is that right?

False alarme…

Fatal error: Class ‘Image’ not found in /Users/thiagoprado/Documents/yii/thiago/protected/models/_base/BaseArquivo.php on line 177




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

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

                    $img = new Image( );  //// THE LINE 177 ////

                    $img->size = $image["size"];

                    $img->mime = $image["mime"];

                    $img->name = $image["name"];

                    $img->source = "/images/uploads/{$this->id}/".$image["filename"];

                    $img->arquivo_id = $this->id;

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



Depends on what you are doing, and if you are using giix, you shouldn’t be modifying the basemodel


/**

 * This is the model base class for the table "Arquivo".

 * DO NOT MODIFY THIS FILE! It is automatically generated by giix.

If it worked with the default XUploadForm, then you have something wrong with your code.

Worked!!!!

Now that I can create how to configure an update?

Model 1 - User

Model 2 - Archive with user_id as parent

Thanks

hi!

the extension is great and works well, thank you for your nice work. but I had to expand it to fit my project’s needs, so I have some issues now.

first of all, is there any way to have two or more widgets in a form, each sending their requests to their respective action?

I have tried it but there are major conflicts when two widgets are loaded on the screen.

I actually want to have different actions for different scenarios, for example one for files, one for images, and one for gallery, all related to a news article.

so even if it is possible to have one widget on the screen, but somehow change the action it is sending requests in the runtime, my problem is solved! is there anyway?

thank you in advance.

This should be something related to the javascript I believe, I have never used 2 widgets in the same page so I can’t really tell, but you can check this wiki and see if you can workout something, if you do, maybe you can also contribute your code in the git repo

thanks for your fast response!

I had a look, as you’ve probably noticed, it has duplicated the whole form, and then used the same class for those two. in my case, the widgets are embedded in one form, beside other model attributes, and it doesn’t feel good to have multiple forms in one view for one model! :-? and even if I do so, I’ll had to edit your code in XUpload.php, where you have registered the starter JS for this plugin.

what about the second way? is there any DOM attribute anywhere holding the destination action, so wen can change it in client side? like by checking a checkbox, that attribute would change from ‘uploadImage’ to ‘uploadFile’ ?

alternatively, I’ll try to solve this problem using bootstrap tabs, having different form in each tab, and hoping that no conflicts would happen :)