Yii文件上传未验证文件类型

时间:2013-05-05 08:47:54

标签: file validation upload yii

我正在验证要上传的文件类型。验证规则似乎不起作用。我只想接受jpg文件,但是当我尝试输入pdf文件时,它仍然接受它并且不会给出任何错误。请帮忙。我不知道我做错了什么。

查看:

<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'document-form',
'enableAjaxValidation'=>true,
'enableClientValidation'=>true,
'clientOptions'=>array('validateOnSubmit'=>true), //This is very important
'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,'barangay_clearance'); ?>
    <?php echo $form->fileField($model,'barangay_clearance'); ?>
    <?php echo $form->error($model,'barangay_clearance'); ?>
</div>

<div class="row buttons">
    <?php echo CHtml::submitButton($model->isNewRecord ? 'Create' : 'Save'); ?>
</div>

<?php $this->endWidget(); ?>

型号:

public function rules()
{
    // NOTE: you should only define rules for those attributes that
    // will receive user inputs.
    return array(
        array('barangay_clearance', 'file', 'allowEmpty'=>true, 'types'=>'jpg', 'message'=>'Jpg files only', 'on'=>'insert'),
        array('barangay_clearance, barangay_status, zoning_clearance, zoning_status, sanitary_clearance, sanitary_status, occupancy_permit, occupancy_status, fire_safety, fire_safety_status', 'safe'),
        // The following rule is used by search().
        // Please remove those attributes that should not be searched.
        array('document_id, business_id, barangay_clearance, barangay_status, zoning_clearance, zoning_status, sanitary_clearance, sanitary_status, occupancy_permit, occupancy_status, fire_safety, fire_safety_status', 'safe', 'on'=>'search'),
    );
}

控制器:(注意:除了激活ajaxvalidation函数和创建另一个模型的实例外,我还没有真正更改过控制器)

public function actionCreate($id)
{
    $model=new Document;
    $busModel = Business::model()->findByPk($id);

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

    if(isset($_POST['Document']))
    {
        $model->attributes=$_POST['Document'];
        if($model->save())
            $this->redirect(array('view','id'=>$model->document_id));
    }

    $this->render('create',array(
        'model'=>$model,
        'busModel'=>$busModel,
    ));
}

2 个答案:

答案 0 :(得分:5)

这应该完美。

array('barangay_clearance', 'file','types'=>'jpg', 'allowEmpty'=>true, 'on'=>'update', 'on'=>'insert'),

答案 1 :(得分:0)

您没有将任何方案分配给模型。如果您在表单窗口小部件中使用的模型是Document的实例,那么:

$model=new Document;

必须替换为:

$model=new Document('insert');

自规则声明

array('barangay_clearance', 'file', 'allowEmpty'=>true, 'types'=>'jpg', 'message'=>'Jpg files only', 'on'=>'insert'),

表示它只会应用于“插入”方案。

我希望它有所帮助。