yii multiple file upload

Posted on April 25, 2012. Filed under: Uncategorized | Tags: |

when we want to upload multiple files yii has gave a full functioning widget called “CMultiFileUpload” http://www.yiiframework.com/doc/api/1.1/CMultiFileUpload
but the documentation is no clear …
we can’t find there how to catch up uploaded  files and how to save them a directory we need.

let’s see how we do this..

my example is how to upload my product images to my images directory created in my application path(in protected folder)

in my view file put this code as form field
here i use only 3 fields, name field,  images field and price field.

<!–?                        php $form=$this->beginWidget(‘CActiveForm’, array(
‘id’=>’product-form’,
‘enableAjaxValidation’=>false,
‘htmlOptions’ => array(‘enctype’ => ‘multipart/form-data’),
)); ?>

<p>Fields with <span>*</span> are required.</p>

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

<div>
<!–?php echo $form->labelEx($model,’name’); ?>
<!–?php echo $form->textField($model,’name’,array(‘size’=>60,’maxlength’=>255)); ?>
<!–?php echo $form->error($model,’name’); ?>
</div>

<div>
<!–?php echo $form->labelEx($model,’product_images’); ?>
<!–?php $this->widget(‘CMultiFileUpload’,array(
‘name’=>’other_product_images’,
‘accept’=>’jpg|png’,
‘max’=>5,
‘remove’=>Yii::t(‘ui’,’Remove’),
‘denied’=>’type is not allowed’, //message that is displayed when a file type is not allowed
‘duplicate’=>’file appears twice’, //message that is displayed when a file appears twice
‘htmlOptions’=>array(‘size’=>25),
)); ?>
<!–?php echo $form->error($model,’product_images’); ?>
</div>

<div>
<!–?php echo $form->labelEx($model,’price’); ?>
<!–?php echo $form->textField($model,’price’,array(‘size’=>10,’maxlength’=>10)); ?>
<!–?php echo $form->error($model,’price’); ?>
</div>

<div>
<!–?php echo CHtml::submitButton($model->isNewRecord ? ‘Create’ : ‘Save’); ?>
</div>

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

</div><!– form –>

this  widget send an array of uploaded files
the name of that array we define in ‘name’ element.
we can catch up it in the controller using

CUploadedFile::getInstancesByName() method

$product_images = CUploadedFile::getInstancesByName(‘product_images’);

this is return an array of CUploadedFile instances

we can access each instance through foreach loop

foreach ($primary_product_image as $image => $pic) {

  we can save the current image at any where
  $pic->saveAs(Yii::getPathOfAlias(‘application’).’/images/original_images/’.$pic->name);

}

Advertisements
Read Full Post | Make a Comment ( None so far )

Liked it here?
Why not try sites on the blogroll...