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.
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
));
?>
View correction
The example is not working for me, so i've added in the view:
'name'=>'photos',
and now it works...
RE: #16982
Yes Indeed!
There are two corrected ways:
a)
'name'=>'photos' and $photos = CUploadedFile::getInstancesByName('photos');
b)
'model'=>$model,'attribute'=>'photos', and $photos = CUploadedFile::getInstancesByName('Photo[photos]');
If you have any questions, please ask in the forum instead.
Signup or Login in order to comment.