Validation error on file upload: Only files with these extensions are allowed...

Hello :)

I have ActiveRecord model. I have rules in controller setup to allow form uploading only files with "*.sul" extensions:


	public function rules(){

		return [

			[['name', 'version', 'description', 'filename'], 'required'],

			[['filename'], 'file', 'skipOnEmpty' => false, 'extensions' => 'sul'],

			[['filename'], 'unique']

		];

	}

But when I try to upload file i get validation error:


Only files with these extensions are allowed: sul.

What is going on? Didn’t I just allowed upload of sul files in rules()?

My action looks like this:




	public function actionAdd(){

		$package = new MyPackage();


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

			$post = Yii::$app->request->post();

			if (!empty($post)){

				$package->load($post);

				$package->filename = UploadedFile::getInstance($package, 'filename');

				if ($package->validate()){

					$uploadDir = Yii::$app->basePath . DIRECTORY_SEPARATOR . 'uploads';

					if ($package->filename->saveAs($uploadDir . DIRECTORY_SEPARATOR . $package->filename->baseName . '.' . $package->filename->extension)){

						if ($package->save(false)){

							$this->redirect('/packages/package/index');

						}

					}

				}

			}

		}


		return $this->render('add', [

			'model' => $package,

		]);

	}

// edit

Why my code is working perfectly fine when I change "sul" to "txt"?


[['filename'], 'file', 'skipOnEmpty' => false, 'extensions' => 'txt'],

I’m running into the same problem! Did you figure it out?

I ended up setting checkExtensionByMimeType to false in my validation rules.

https://www.yiiframework.com/doc/api/2.0/yii-validators-filevalidator#$checkExtensionByMimeType-detail

2 Likes

Thank you! This helped me