Multiple files uploader with CMultiFileUpload

You are viewing revision #3 of this wiki article.
This version may not be up to date with the latest version.
You may want to view the differences to the latest version.

next (#4) »

Today I will show you how to handle multiple file upload step by step.

In your controller.

public function actionCreate()

    {
        $model = new Photo;
        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);
        $type = isset($_GET['type']) ? $_GET['type'] : 'post';

        if (isset($_POST['Photo'])) {

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

            $photos = CUploadedFile::getInstancesByName('photos');
 
            // proceed if the images have been set
            if (isset($photos) && count($photos) > 0) {
 
                // go through each uploaded image
                foreach ($photos as $image => $pic) {
                    echo $pic->name.'<br />';
                    if ($pic->saveAs(Yii::getPathOfAlias('webroot').'/photos/path/'.$pic->name)) {
                        // add it to the main model now
                        $img_add = new Photo();
                        $img_add->filename = $pic->name; //it might be $img_add->name for you, filename is just what I chose to call it in my model
                        $img_add->topic_id = $model->id; // this links your picture model to the main model (like your user, or profile model)
 
                        $img_add->save(); // DONE
                    }
                    else{
                        echo 'Cannot upload!'
                    }
                }
            }

            if ($model->save())
                $this->redirect(array('update', 'id' => $model->id));
        }
        $this->render('create', array(
            'model' => $model,

        ));

    }

In your view:

<?php
  $this->widget('CMultiFileUpload', array(
     'model'=>$model,
     'attribute'=>'photos',
     'accept'=>'jpg|gif|png',
     'options'=>array(
        // 'onFileSelect'=>'function(e, v, m){ alert("onFileSelect - "+v) }',
        // 'afterFileSelect'=>'function(e, v, m){ alert("afterFileSelect - "+v) }',
        // 'onFileAppend'=>'function(e, v, m){ alert("onFileAppend - "+v) }',
        // 'afterFileAppend'=>'function(e, v, m){ alert("afterFileAppend - "+v) }',
        // 'onFileRemove'=>'function(e, v, m){ alert("onFileRemove - "+v) }',
        // 'afterFileRemove'=>'function(e, v, m){ alert("afterFileRemove - "+v) }',
     ),
     'denied'=>'File is not allowed',
     'max'=>10, // max 10 files


  ));
?>

Reference: http://www.codexamples.com/94/cmultifileupload/

5 0
8 followers
Viewed: 282 055 times
Version: Unknown (update)
Category: How-tos
Written by: Interboy
Last updated by: samdark
Created on: Sep 27, 2013
Last updated: 5 years ago
Update Article

Revisions

View all history

Related Articles