我想上传多个图片并将图片名称保存到数据库表中。表格中有两个属性 - id
和image_name
。在表单中,我使用CMultifileupload
小部件上传图像数量。当我提交表格时,没有任何效果。然后我尝试回应if (isset($_POST['ImageTemp'])) {
下面的某些东西,但没有效果。所以我暂时看看输出是否有多个图像上传。但是,我写道:
形式:
<div class="form form-custom">
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'image-temp-form',
'enableAjaxValidation'=>false,
'htmlOptions'=>array('enctype'=>'multipart/form-data' ),
)); ?>
<p class="note">Fields with <span class="required">*</span> are required.</p>
<?php echo $form->errorSummary($model); ?>
<div class="row">
<?php echo $form->labelEx($model,'image_name'); ?>
<?php
$this->widget('CMultiFileUpload', array(
'model'=>$model,
'attribute'=>'image_name',
//'name' => 'files',
'accept'=>'jpg|gif|png',
'denied'=>'File is not allowed',
'max'=>3, // max 10 files
));
?>
<?php echo $form->error($model,'image_name'); ?>
</div>
<div class="row buttons">
<?php echo CHtml::submitButton($model->isNewRecord ? 'Create' : 'Save'); ?>
</div>
<?php $this->endWidget(); ?>
</div><!-- form -->
控制器中的:
public function actionCreate()
{
$model=new ImageTemp;
$type = isset($_GET['type']) ? $_GET['type'] : 'post';
if (isset($_POST['ImageTemp'])) {
echo "something but no output";
$model->attributes = $_POST['ImageTemp'];
$photos = CUploadedFile::getInstancesByName('image_name');
// 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').'/images/project'.$pic->name)) {
// add it to the main model now
$model->image_name = $pic->name; //it might be $img_add->name for you, filename is just what I chose to call it in my model
$model->save(); // DONE
}
else{
echo 'Cannot upload!';
}
}
}
}
$this->render('create',array(
'model'=>$model,
));
}
在模型中,我写了规则:
public function rules()
{
return array(
array('image_name', 'file','types'=>'jpg, gif, png', 'allowEmpty'=>true, 'on'=>'update'),
// The following rule is used by search().
// @todo Please remove those attributes that should not be searched.
array('id, image_name', 'safe', 'on'=>'search'),
);
}
我正在尝试基于this,但不明白我做错了什么。
答案 0 :(得分:1)
$_FILES['ImageTemp']
是你的朋友;)
所以在你的控制器中你应该做
if (isset($_FILES['ImageTemp'])) {
// do something..
}