Got issue with file extension validator

Hi, I got an issue while I was using File Validator extension. I make an import feature. When I set rule to validate file extension is sql, I get a error message "Only files with these extensions are allowed: sql". This is my code

Controller


public function actionIndex()

{

    $model = new BackupForm();

    if (Yii::$app->request->isPost) {

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

        if ($model->import()) {

            Yii::$app->session->setFlash('success','Import successful');

        }

    }

    

    return $this->render('index', ['model' => $model]);

}

Model


class BackupForm extends Model

{

    

    public $importFile;


    public function rules()

    {

        return [

            [['importFile'], 'file', 'skipOnEmpty' => false, 'extensions' => 'zip, sql']

        ];

    }

    

    public function import()

    {

        if (!$this->validate()) {

            return false;

        }

        // Execute importing

    }

}

View


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

    <h3>Import data</h3> 

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

    <div class="form-group">

        <?= Html::submitButton('Import', ['name' => 'import', 'value' => 'import']) ?>

    </div>

<?php ActiveForm::end(); ?>

I have try to investigate the cause of this. But I don’t find yet. If you have experience and know the reason. Please help me!

Finally, I have found the solution is set checkExtensionByMimeType to false.


public function rules()

{

    return [

        [

            ['importFile'], 'file', 'skipOnEmpty' => false,

            'extensions' => 'zip, sql' ,

            'checkExtensionByMimeType' => false

        ]

    ];

}

1 Like

As you can see in your rules function, you defined that only .zip and .sql files are allowed for upload. If you try to upload an image, then you will get the error you wrote. Change the following line:


            [['importFile'], 'file', 'skipOnEmpty' => false, 'extensions' => 'zip, sql']

To


            [['importFile'], 'file', 'skipOnEmpty' => false, 'extensions' => 'jpg, jpeg, gif, png']

and everything should be fine.

Hi, I got error message when I try to upload an sql file, not an image. I have fixed it in my second post way. BTW, thank for your care.