I'm trying to upload a file in yii2
, the same code was working fine before, but for some reason, I can't figure out stopped working after a lot of checks. I notice the validate method of the upload model is returning false
, and in the error message it says:
Array ( [file] => Array ( [0] => Only files with these extensions are allowed: png, jpg, jpeg, gif, pdf. ) )
However, the weirdest thing is, I uploaded a JPG file. I also try to upload a PNG file, but I get the same error. When I remove the check for extension in the model rules, it works fine, or totally removing the validation also works, I don't know what I'm missing here? Any help would be appreciated.
NOTE:
With the validation or the extension check for extension in place, the codes in the if()
statement fail to execute, but rather the else statement executes, removing the validation or the extension check the code in if()
works fine:
<?php
class Upload extends Model
{
public $file;
public $randomCharacter;
public $fileDirectory;
public function rules()
{
return [
[['file'], 'file', 'skipOnEmpty' => false, 'maxSize' => 1024 * 1024 * 2, 'extensions' => ['png, jpg, jpeg, gif, pdf']],
];
}
public function upload($uploadPath = NULL)
{
if (isset($uploadPath) && $uploadPath !== NULL) {
$filePath = $uploadPath;
} else {
$filePath = "@frontend/web/uploads/";
}
//generate random filename
$rand = Yii::$app->security->generateRandomString(10) . '_' . time();
//assign generated file name to randomCharacter property
$this->randomCharacter = $rand;
//define the upload path;
if ($this->validate()) {
$path = \Yii::getAlias($filePath);
$this->fileDirectory = $this->randomCharacter . '.' . $this->file->extension;
echo $path . $this->fileDirectory;
exit;
$this->file->saveAs($path . $this->fileDirectory);
return true;
} else {
// return false;
//with validation in place, the else statement is executed
print_r($this->getErrors());
exit;
}
}
}
Remove the straight brackets of attribute "extensions"
Instead of:
[['file'], 'file', 'skipOnEmpty' => false,'maxSize'=>1024 * 1024 * 2, 'extensions'=> ['png, jpg,jpeg,gif,pdf']],
You should have this:
[['file'], 'file', 'skipOnEmpty' => false,'maxSize'=>1024 * 1024 * 2, 'extensions'=> 'png, jpg, jpeg, gif, pdf'],