yii初学者 2016-12-12 16:58:50 6848次浏览 3条回复 0 0 0

模型:

class UploadForm extends Model
{
    /**
     * @var UploadedFile file attribute
     */
    public $file;

    /**
     * @return array the validation rules.
     */
    public function rules()
    {
        return [
            [['file'], 'file', 'extensions' => 'jpg, png']];
    }
}

视图:

<?php

use yii\widgets\ActiveForm;

?>
<?php $form = ActiveForm::begin([ 'options' => ['enctype' => 'multipart/form-data'],]) ?>

<?=$form->field($model,'file')->fileInput();
?>

    <button>Submit</button>

<?php ActiveForm::end() ?>

控制器:

public function actionUpload()
{
    $model = new UploadForm();
    if (Yii::$app->request->isPost) {
        $model->file = UploadedFile::getInstance($model, 'file');
        $filePath = $this->fileExists(Yii::$app->basePath . '/web/uploads/');

        if ($model->file && $model->validate()) {
            $model->file->saveAs($filePath . $model->file->baseName . '.' . $model->file->extension);
        }
        var_dump($model->file->extension);
        echo '<br>';
        var_dump($model->validate());
        echo '<br>';
        var_dump($model->errors);

    } else {
        return $this->render('upload', ['model' => $model]);

    }

}

为何验证的结果一直为false? 输出结果为:

string(3) "jpg" 
bool(false) 
array(1) { ["file"]=> array(1) { [0]=> string(59) "只允许使用以下文件扩展名的文件:png, jpg。" } }

文件类型对了,还是显示为错的 php.ini里面也配置了

extension=php_fileinfo.dll

为何验证不过?

您需要登录后才可以回复。登录 | 立即注册