Uploading multiple images with CMultiFileUpload

You are viewing revision #1 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 (#2) »

  1. View
  2. Controller

"The documentation for CMultiFileUpload isn't clear!"

"I don't know where the uploaded files went!"

"How can I save those files I uploaded in the right directory!"

"!@!##!!!!"

I understand your pain.

I went through a weeks worth of frustration that was unnecessary, so for your benefit, here are the steps towards the uploading of images via CMultiFileUpload so you can focus on the more important thing: your actual work.

  • Database - a user table, and a picture table, with the picture table linking (via a foreign key) back to the user table. More simplified versions (just uploading straight to a picture table) can be easily discerned via this specialized example.
  • Relations - So, given the above assumption, through the 'relations' function that gii (for example) auto-creates for you, you will be able to access your pictures like so: $model->pictures

View

In _form.php:

  • You have to add "multi-part/form-data" to your _form.php file, by two methods: either add the following modification to your header
<?php $form=$this->beginWidget('CActiveForm', array(
	'id'=>'topic-form',
	'enableAjaxValidation'=>false,
    'htmlOptions' => array('enctype' => 'multipart/form-data'), // ADD THIS
)); ?>

or this way, before your use of CMultiFileUpload

<?php echo CHtml::form('','post',array('enctype'=>'multipart/form-data')); ?>

The actual CMultiFileUpload implementation is this way:

$this->widget('CMultiFileUpload', array(
                'name' => 'images',
                'accept' => 'jpeg|jpg|gif|png', // useful for verifying files
                'duplicate' => 'Duplicate file!', // useful, i think
                'denied' => 'Invalid file type', // useful, i think
            ));

Controller

Algorithm:

  1. load the model in question

  2. check if the model is set

  3. get your uploaded images

  4. save each image in the appropriate place on your server

  5. create new instantiation of your picture model

  6. save that instantiation

  7. save the rest of the data you used in your form

  8. onto the next headache

Before we go on, both your actionCreate() and actionUpdate() methods need to access the folder where you are saving your image. How you handle the OOP design is up to you, but here's the code to create the directory, as well as creating it if it wasn't done already:

// make the directory to store the pic:
                if(!is_dir(Yii::getPathOfAlias('webroot').'/images/ADD YOUR PATH HERE!/'.$model->name)) {
                    mkdir(Yii::getPathOfAlias('webroot').'/images/ADD YOUR PATH HERE!/'.$model->name))
                    chmod(Yii::getPathOfAlias('webroot').'/images/ADD YOUR PATH HERE!/'.$model->name)), 0755); // the default implementation makes it under 777 permission, which you could possibly change recursively before deployment, but here's less of a headache in case you don't
                }

Now in your actionUpdate(), or actionCreate():

$model=$this->loadModel($id);

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

		if(isset($_POST['Topic'])) {
            
			$model->attributes=$_POST['Topic'];

            // THIS is how you capture those uploaded images: remember that in your CMultiFile widget, you set 'name' => 'images'
            $images = CUploadedFile::getInstancesByName('images');

            // proceed if the images have been set
            if (isset($images) && count($images) > 0) {

                // go through each uploaded image
                foreach ($images as $image => $pic) {
                    echo $pic->name.'<br />';
                    if ($pic->saveAs(Yii::getPathOfAlias('webroot').'/images/ADD YOUR PATH HERE!/'.$model->name)) {
                        // add it to the main model now
                        $img_add = new Picture();
                        $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
                        // handle the errors here, if you want
                }

                // save the rest of your information from the form
                if ($model->save()) {
                    $this->redirect(array('view','id'=>$model->id));
                }
            }
        }

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

Obviously, you have to handle the errors, but that's up to you (I haven't coded that yet). However, now you have the files uploaded to your model, and you can play around with it