我是 yii 的新手,所以我一直在关注这个教程。
当我尝试上传图片时,即使不是,它也会报告空字段。
我的 _form 视图:
<div class="form">
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'picture-form',
'enableAjaxValidation'=>false,
'htmlOptions' => array('enctype' => 'multipart/form-data'),
));
?>
...
<div class="row">
<?php echo $form->labelEx($model,'path_to'); ?>
<?php echo $form->fileField($model,'path_to'); ?>
<?php echo $form->error($model,'path_to'); ?>
</div>
...
<?php $this->endWidget(); ?>
</div><!-- form -->
这是我的操作方法:
public function actionCreate()
{
$model=new Picture;
if(isset($_POST['Picture']))
{
$model->attributes=$_POST['Picture'];
$model->picture=CUploadedFile::getInstance($model,'path_to');
if($model->save()){
$log->lwrite('in save'.$model->picture);
$model->picture->saveAs(Yii::app()->basePath.'/../images/'.$model->picture);
$this->redirect(array('view','id'=>$model->id));
$log->lclose();
}
}
$this->render('create',array('model'=>$model,));
}
当我 print_r($_FILES) 的所有内容时,当我 print_r($_POST) 字段“path_to”为空时,验证器可能正在选择该字段。
我可能在这里遗漏了一些东西,我一无所知。
update1:我注意到 yii 使用与文件输入同名的隐藏字段,而不是从 $_POST 读取属性,这导致引擎读取空隐藏字段。我知道当用户不输入新图片时,隐藏字段会更新。谁能建议上传图片的最佳方式是什么?
update2:型号代码:类图片扩展CActiveRecord {
public $picture;
...
public function rules()
{
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
array('path_to, page_id', 'required'),
array('page_id', 'numerical', 'integerOnly'=>true),
array('alt_text', 'safe'),
// The following rule is used by search().
// Please remove those attributes that should not be searched.
array('id, alt_text, path_to, page_id', 'safe', 'on'=>'search'),
//array('path_to', 'file','types'=>'jpg, gif, png', 'allowEmpty'=>true, 'on'=>'update'),
//array('path_to', 'length', 'max'=>255, 'on'=>'insert,update'),
array('path_to', 'unsafe'),
);
}
...
最好的!