My Google+ Profile

Monday 23 April 2012

This article is used for upload multiple files and moved them to particular folder and stored that folder path location into database table in Yii application.

First of all, Make following changes to your model file.

model.php

    public function rules()
    {
        // NOTE: you should only define rules for those attributes that
        // will receive user inputs.
        return array(
            array('image', 'required'),
//            array('image', 'length', 'max'=>300),
            array('image', 'file', 'types'=>'jpeg, gif, png'),
   
            // The following rule is used by search().
            // Please remove those attributes that should not be searched.
            array('id, image', 'safe', 'on'=>'search'),
        );}


Then, Make this changes in view file.


_form.php


    <div class="row">
        <?php echo $form->labelEx($model,'image'); ?>
        <?php $this->widget('CMultiFileUpload', array(
                'name' => 'image123',
        'model'=>$model,
            'attribute'=>'image',
        'accept' => 'jpeg|jpg|gif|png', // useful for verifying files
                'duplicate' => 'Duplicate file!', // useful, i think
                'denied' => 'Invalid file type', // useful, i think
            ));
        ?>
    </div>

Make following changes to your controller.

controller.php

    public function actionCreate()
    {
        $model=new PhotoUploadTable;

        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);

        $images = CUploadedFile::getInstancesByName('image');

        if($images != null)
        {
                       if(isset($_POST['PhotoUploadTable']))$model->attributes=$_POST['PhotoUploadTable'];
            foreach($images as $list=>$pic)            {
               $model->setIsNewRecord(true);
              $model->id=null;
             $model->image = $pic;  
             $model->save();
             $model->image->saveAs(Yii::getPathOfAlias('webroot').'/images/' .$model->image);

            }
                $this->redirect(array('index'));
          
        }

        $this->render('create',array(
            'model'=>$model,
        ));

    }

This works perfectly for me. I hope this will help you.

Karmraj.

No comments:

Post a Comment