检查CodeIgniter文件上传功能中的文件名


Check the file name in CodeIgniter file upload function

我使用以下CodeIgniter函数上传文件,效果很好:

function uploadFiles(){
         $this->load->library('upload');
         $error = 0;    
         $projectName = $_POST['projectname'];
         $projectID = $_POST['maxid'];
         $folderName = $this->config->item('upload_dest')."/".$projectName."_".$projectID;
         if(!file_exists ($folderName)){
             $aa = mkdir($folderName);
         }
         $config['upload_path']   = $folderName;
         $config['allowed_types'] = 'xml';
         //$config['allowed_types'] = '*';
         $config['max_size']      = '0';
         $config['overwrite']     = TRUE;
         $this->upload->initialize($config);
         for($i=0; $i<count($_FILES['files']['name']); $i++)
         {
           $_FILES['userfile']['name']    = $_FILES['files']['name'][$i];
           $_FILES['userfile']['type']    = $_FILES['files']['type'][$i];
           $_FILES['userfile']['tmp_name'] = $_FILES['files']['tmp_name'][$i];
           $_FILES['userfile']['error']       = $_FILES['files']['error'][$i];
           $_FILES['userfile']['size']    = $_FILES['files']['size'][$i];
              if($this->upload->do_upload())
              {
                $error += 0;
              }else{
                $error += 1;
              }
         }
         if($error > 0){ 
            $this->upload->display_errors();
            return FALSE; 
         }
         else{ 
            return TRUE; 
         }
    }

我需要做的是——检查以确保至少有一个正在上传的文件名为"etl"。如果用户选择的文件列表中没有这样的文件,请停止操作,不要上传任何内容,并返回表单验证错误。有人能就此提出建议吗?

谢谢。

首先,从php无法在上传之前获得文件的名称,必须上传才能获得文件的属性。因此,可用的选项有:

(1) 允许上传文件,然后获取名称并检查是否有包含"etl"的文件。如果非包含您要查找的内容,则删除刚刚上传的文件,并自行设置自定义错误消息。这种方法有一个非常大的开销成本,允许你首先上传不需要的东西,然后删除它。非常差,但解决了问题。

(2) 另一方面,是javascript解决方案。为上传字段指定一个通用类名例如"userfile1"、"userfile2"、。。。。。。。

然后从您的javascript和使用jquery,截取表单的提交,然后使用for循环来获取每个文件上传字段的值,从中可以获得文件的全名和扩展名,然后进行"etl"比较。

<script type="text/javascript" >
  $("#formname").submit(function(){
    $(".classname").each(function(){
      if($(this).val().indexOf("etl") != -1 ){
        return true;
      }
    });
    /*
     *whatever makes it finish executing that loop and the execution of code gets 
     *to this point, then the string "etl" was not found in any of the names.
     */
     // write a piece of code to show an hidden error field
     $("#hidden_error_div").text("Your error message").show();
     return false;  //makes sure the form is not submitted.
  });
</script>

希望这能有所帮助。

Oyekumi提供了一个很好的javascript解决方案,可以在它真正到达服务器之前进行拦截。正如Oyekumi所指出的,一旦它到达那里,它就会作为一个包到达那里,所以你可以将它存储和处理在一个临时目录中,评估那里的每个文件并进行相应的处理。