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.




<form>

    <?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)));  ?>

</form>



Controller action




public function actionContact()

        {

            $model= new Message;

            $name=$_REQUEST['name'];

            if(isset['$_REQUEST['name'])

            {

               $model->name=$name;

               $model->save();

            }

         }



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

http://www.yiiframework.com/wiki/2/how-to-upload-a-file-using-a-model/

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


if($model->save())

     {....

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 :)

http://www.tizag.com/phpT/fileupload.php

In Yii how it possible?

http://www.yiiframew…ileField-detail

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(

    'id'=>'verticalForm',

    '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'); ?>

</div>



Then in your controller you can use something like




public function actionCreate()

	{

		$model=new NewTask;

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

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

		{

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

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

			$nf = $model->file_name;

			if($model->save())

			{

				$model->file_name->saveAs($dir.'/'.$fn);

				$model->file_name = $fn;

				$model->save();

........



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',

				'types'=>'xml',),

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

				'allowEmpty'=>true,

				'types'=>'xml',),

.....



Read CUploadedFile

Thanks for all rplys.