简体   繁体   中英

Yii2 file upload is not validating file type

My Model code,

public function rules()
{
    return [            
        [['image'], 'safe'],
        ['image', 'file', 'types'=>'jpg, gif, png'],
    ];
}

Use Apartfrom types,validation message not display document save in database

To validate file type you should use property $extensions of FileValidator.

public function rules()
    {
        return [

            [['image'], 'safe'],
            [['image'], 'file', 'extensions'=>'jpg, gif, png'],
        ];
    }

Update

Ok, I've got this. Please check one more time the source link, especially the controller section. To validate your model, you have to use validate() function.

Example code:

$model->file = UploadedFile::getInstance($model, 'file');

if ($model->file && $model->validate()) {                
    $model->file->saveAs('uploads/' . $model->file->baseName . '.' . $model->file->extension);
}

Source.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM