Subir ficheros en Yii Framework

Veamos como subir ficheros en Yii framework.

El controlador:

1public function actionIndex(){
2 
3        $form=new UsuariosForm();
4         
5        if(isset($_FILES["UsuariosForm"])){
6             
7            //Instanciamos el subidor para el campo fichero del formulario
8            $file=CUploadedFile::getInstance($form,"fichero");
9             
10            //Nombre del fichero
11            $name=time()."-".$file->getName();
12                    //$file->getExtensionName()
13            
14            //Permitimos tres tipos de fichero
15            if($file->getExtensionName()=="png" || $file->getExtensionName()=="pdf" || $file->getExtensionName()=="zip"){
16                 
17                //Guardamos el fichero
18                $file->saveAs(Yii::getPathOfAlias("webroot")."/uploads/".$name);
19                 
20            }else{
21                //Crear mensaje flash
22                Yii::app()->user->setFlash('mensaje','Solo ficheros png, pdf o zip');
23                 
24                //Refrescamos pantalla
25                $this->refresh();
26            }
27       }
28        $this->render('index',array(
29                    "form"=>$form
30                ));
31}

La vista:

1<h1>Subir ficheros con Yii</h1>
2<?php echo CHtml::beginForm('','post',array("name"=>"form","id"=>"form","enctype"=>"multipart/form-data"));?>
3    Fichero ( Png, pdf o zip )
4    <?php
5    echo CHtml::activeFileField($form,"fichero");
6    ?>
7    <br/>
8    <?php echo CHtml::submitButton('submit',array("class"=>"btn btn-success","value"=>"Subir","title"=>"Subir")); ?>
9    <?php if(Yii::app()->user->hasFlash('mensaje')){
10    //Mostrar mensaje flash
11    ?>
12    <span class="alert alert-danger"><?php echo Yii::app()->user->getFlash('mensaje')?></span>
13<?php } ?>
14<?php echo CHtml::endForm();?>

El mensaje de error flash solo se muestra una vez.
subir ficheros en yii framework

Más información:
http://www.yiiframework.com/wiki/2/how-to-upload-a-file-using-a-model/
http://www.yiiframework.com/wiki/21/how-to-work-with-flash-messages/

Víctor Robles WEB

Autor: Victor

Desarrollador web - Formador online - Blogger

Compartir este post