Uploading multiple images with CMultiFileUpload

29 followers
  • "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!/'.$pic->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

Hat-tip: Wiseon3 caught a copy/paste error of mine:

"if ($pic->saveAs(Yii::getPathOfAlias('webroot').'/images/ADD YOUR PATH HERE!/'. $model->name)) {
               // add it to the main model now"

has been updated to

if ($pic->saveAs(Yii::getPathOfAlias('webroot').'/images/ADD YOUR PATH HERE!/'. $pic->name)) {
                        // add it to the main model now

The main code has been updated to reflect this change. Thanks

Total 5 comments

#7064 report it
yureshwar at 2012/02/22 02:34am
Not working if i declare model and attribute

Hi,

Here is the code for my form

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

My controller for actionCreate i have included model2 while rendering the form.

$model2=new Images
if(isset($_POST['Images'])
{
  $model2->attributes=$_POST['Images'];
}

It gives me error like this when i submit the form.

Undefined Index Images

And if i comment the

if(isset($_POST['Images'])
{
  $model2->attributes=$_POST['Images'];
}

and continuing to the rest of the like this

$images=CUploadedFile::getInstancesByName($model2,'filename');

It gives me this error

strlen($name) expects string object given.

Can anyone help me how to handle through models.

#5208 report it
pligor at 2011/09/22 05:40am
Validator

At first I thought it would need a custom validator but finally the 'file' validator does the job.

If you want to upload multiple files then you MUST SET maxFiles parameter.

For example for an attribute named 'files' a rule would look like this:

array(
                'files',
                'file',
                'allowEmpty' => false,
                'maxFiles' => 14,
                //'tooMany' => 'some error message',
                'maxSize' => 10*(1024*1024),    //10MB
                //'tooLarge' => 'some error message',
                'minSize' => 1024,  //1KB
                //'tooSmall' => 'some error message',
                //'types' => $this->types,  //extension names separated by space or comma
                //'wrongType' => 'some error message',
            ),

As you can see I commented out the types attribute because this is already checked from CMultiFileUpload ;)

Without setting maxFiles I would get an error at validation that the 'files' attribute is blank!

#4545 report it
dRock at 2011/07/19 07:40am
If $images is coming up empty

You can also do:

$images = CUploadedFile::getInstances($model,'images');
#4099 report it
zealotous at 2011/06/06 01:16am
Advice

Don't forget to change post_max_size, upload_max_filesize parameters in you php.ini. There is can be problems with big files uploading.

#php.ini
post_max_size = 16M
upload_max_filesize = 16M
#3517 report it
Wiseon3 at 2011/04/17 05:23am
Correction image name

Shouldn't it be $pic->name in the $pic->saveAs() function, instead of $model->name?

So instead of

if ($pic->saveAs(Yii::getPathOfAlias('webroot').'/images/ADD YOUR PATH HERE!/'.$model->name))

it would be

if ($pic->saveAs(Yii::getPathOfAlias('webroot').'/images/ADD YOUR PATH HERE!/'.$pic->name))

Leave a comment

Please to leave your comment.