如何解决yii2中的文件上传验证问题

如何解决yii2中的文件上传验证问题,yii2,Yii2,我试图在yii2中上载一个文件,之前相同的代码工作正常,但由于某些原因,我无法确定它在经过大量检查后停止工作。我注意到上载模型的验证方法返回false,并且在错误消息中显示Array([file]=>Array([0]=>只允许使用这些扩展名的文件:png、jpg、jpeg、gif、pdf。)但最奇怪的是我上传了一个jpg文件我也尝试上传一个png文件同样的错误,当我删除模型规则中的扩展名检查时,它工作正常或完全删除验证也工作,我不知道这里缺少什么,如果您能帮忙,我们将不胜感激 NOTE //

我试图在yii2中上载一个文件,之前相同的代码工作正常,但由于某些原因,我无法确定它在经过大量检查后停止工作。我注意到上载模型的验证方法返回false,并且在错误消息中显示
Array([file]=>Array([0]=>只允许使用这些扩展名的文件:png、jpg、jpeg、gif、pdf。)
但最奇怪的是我上传了一个jpg文件我也尝试上传一个png文件同样的错误,当我删除模型规则中的扩展名检查时,它工作正常或完全删除验证也工作,我不知道这里缺少什么,如果您能帮忙,我们将不胜感激

NOTE  //with the validation or the extension check for extension in place the codes in the if() 
statement fails to execute but rather the else statement execute, removing the validation or the 
extension check the code in if() works fine   

  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 in executed
            print_r($this->getErrors());
            exit;
        }
       
    }
    
 
    
}


  

删除属性“extensions”的直括号

而不是:

[['file'],'file','skipOnEmpty'=>false,'maxSize'=>1024*1024*2,'extensions'=>['png,jpg,jpeg,gif,pdf']],

您应该有这个:


[['file']、'file'、'skipOnEmpty'=>false、'maxSize'=>1024*1024*2、'extensions'=>'png、jpg、jpeg、gif、pdf']、

您尝试过不使用[]吗
'extensions'=>'png,jpg,jpeg,gif,pdf'
确切地说-它应该是一个带有扩展名的字符串数组,或者只是一个带有扩展名列表的字符串,扩展名列表用逗号和/或空格分隔。@Juan.Queiroz很有效谢谢大家有我的一天,添加它作为答案我会接受它的