2012-02-14 124 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 
} 

有很多的笨功能,可能不需要在這裏重新發明輪子。