File Upload

I want to upload a file using Chtml in Yii. Table have 3 fields( id, name, attachment). In the index.php had following code.


    <?php $name='abcd'; ?>

    <?php echo CHtml::textArea('Text', '',array('maxlength' => 300, 'rows' => 4, 'cols' => 30)); ?>

    <?php  echo CHtml::button('Send', array('submit' => array('site/contact','name'=>$name)));  ?>


Controller action

public function actionContact()


            $model= new Message;








I want to add file attachment to this form. How save the file name in database field and file in folder using chtml?

Hi Rvr101

according to

You can do almost that you want

The extra code you have to write is the save of file name in database by below code

$model->nameImage = $model->image; //add this code



obviously you have to add the extra field named ‘nameImage’ in your AR model

How upload a file without $model in the form?

Using pure php code :)

In Yii how it possible?


Yii allows you to upload a file and store the file name in your database fairly simply. In your view make sure you include ‘multipart/form-data’ - example view

<?php /** @var BootActiveForm $form */

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


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

)); ?>

<div class="row">

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

		<?php echo CHtml::activeFileField($model,'file_name', array("style"=>"color:green;")); ?>

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


Then in your controller you can use something like

public function actionCreate()


		$model=new NewTask;

		$dir = Yii::getPathOfAlias('application.uploads');





			$nf = $model->file_name;




				$model->file_name = $fn;



Obviously you need to set up your database table (in this example file name is stored in attribute file_name). So in your model you can set some rules - in this example I only allow upload of xml files

public function rules()


		return array(

			array('file_name', 'file', 'on'=>'insert',


			array('file_name', 'file', 'on'=>'update',




Read CUploadedFile

Thanks for all rplys.