2012-02-14 152 views
4

我有一个很少输入和文件输入的表单。 我想检查文件输入是否为空。 如果它是空的,不要尝试上传,如果不是,那么尝试上传它。检查文件是否要上传? CodeIgniter

我想是这样的:

$upld_file = $this->upload->data(); 
    if(!empty($upld_file)) 
    { 
    //Upload file 
    } 
+0

你需要告诉我们什么是实际发生错误/不工作。 – KillerX 2012-02-14 12:59:31

+0

其实当我做这个表单时,它似乎工作。此表格用于更改用户的个人资料信息。 我希望当用户不选择任何文件来执行上传文件的代码。 基本上,如果文件输入为空则为chek。 – 2012-02-14 13:04:24

回答

6

你使用CodeIgniter的文件上传类...并在条件语句AHD检查,如果其真正的调用$this->upload->do_upload();

<?php 
if (! $this->upload->do_upload()){ 
    $error = array('error' => $this->upload->display_errors()); 
    $this->load->view('upload_form', $error); 
} 
else{ 
    $data = array('upload_data' => $this->upload->data()); 
    $this->load->view('upload_success', $data); 
} 

的user_guide解释对此进行了详细:http://codeigniter.com/user_guide/libraries/file_uploading.html

然而, 如果你在检查文件是否已经被“上载”又名..提交之前,你调用这个类(不死心塌地肯定你为什么会)。您可以访问PHP的$_FILES超全球..和使用条件来检查,如果大小> 0

http://www.php.net/manual/en/reserved.variables.files.php

更新2:这是实际工作的代码,我用它上的化身使用上传者自己CI 2.1

<?php 
//Just in case you decide to use multiple file uploads for some reason.. 
//if not, take the code within the foreach statement 

foreach($_FILES as $files => $filesValue){ 
    if (!empty($filesValue['name'])){ 
     if (! $this->upload->do_upload()){ 
      $error = array('error' => $this->upload->display_errors()); 
      $this->load->view('upload_form', $error); 
     }else{ 
      $data = array('upload_data' => $this->upload->data()); 
      $this->load->view('upload_success', $data); 
     } 
    }//nothing chosen, dont run. 
}//end foreach 
+0

好的,但如果该字段留空,该怎么办?错误会出现,但是我想do_upload()只有当字段不为空(这意味着用户试图上传他们的配置文件的头像? – 2012-02-14 13:08:15

+2

看到我编辑的答案。使用条件$ _FILES if/else语句。 – gorelative 2012-02-14 13:10:25

+0

谢谢。我这样做: '$ avatar = $ _FILES ['userfile'] ['name']; if(!empty($ avatar)) {//上传文件 }' – 2012-02-14 14:04:50

0

可能确实需要更多信息。但基本上,使用笨上传类做这样的事情:

$result = $this->upload->do_upload(); 

if($result === FALSE) 
{ 

    // handle error 
    $message = $this->upload->display_errors(); 
} 
else 
{ 
    // continue 
} 

有很多的笨功能,可能不需要在这里重新发明轮子。

相关问题