2014-05-11 88 views
0

我想上傳我的上傳目錄中的Excel文件。當我沒有檢查文件擴展名時它正在運行。但是,當我檢查文件擴展名時,它始終顯示無效文件。如何使用檢查文件擴展名來導入CodeIgniter中的Excel文件?

我的代碼如下:

function upload_attendance(){ 
    $config['upload_path'] = './uploads/'; 
    $this->load->library('upload', $config); 
    $allowedExts = array("xls"); 
    $temp = explode(".",$_FILES["file"]["name"]); 
    $extension = end($temp); 
    if(($_FILES["file"]["type"]=="file/xls")&&in_array($extension,$allowedExts)){ 
     if($FILES["file"]["error"]>0){ 
      $data['msg'] = $this->upload->display_errors(); 
      $data['sign'] = 'error_box'; 
      $this->session->set_userdata($data); 
       redirect('attendance/add_attendance');; 
     } 
     else{ 
      echo "Uploaded."; 
     } 
    } 
    else{ 
     $data['msg'] = "Invalid file type.Try to upload a valid file."; 
     $data['sign'] = 'error_box'; 
     $this->session->set_userdata($data); 
      redirect('attendance/add_attendance'); 
    } 
} 

如何檢查之前上傳文件的擴展名?你可以幫幫我嗎?

回答

1

在這一行

if(($_FILES["file"]["type"]=="file/xls")&&in_array($extension,$allowedExts)){ 

你正在檢查這兩個擴展 MIME類型是正確的,但據我所知的Excel MIME不file/xls - >我不知道你在哪裏與想出了。

根據this resource的MIME類型爲Excel文件應該是:

xls application/vnd.ms-excel 
xlt application/vnd.ms-excel 
xla application/vnd.ms-excel 
xlsx application/vnd.openxmlformats-officedocument.spreadsheetml.sheet 
xltx application/vnd.openxmlformats-officedocument.spreadsheetml.template 
xlsm application/vnd.ms-excel.sheet.macroEnabled.12 
xltm application/vnd.ms-excel.template.macroEnabled.12 
xlam application/vnd.ms-excel.addin.macroEnabled.12 
xlsb application/vnd.ms-excel.sheet.binary.macroEnabled.12 

可能是你可以出來只是室內用兩個最常用的,所以application/vnd.ms-excelapplication/vnd.openxmlformats-officedocument.spreadsheetml.sheet(用於> 2007文檔)。

這應該工作:

$mimes = ['application/vnd.ms-excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet']; 
$allowedExts = ['xls', 'xlsx']; 
if (in_array($_FILES['file']['type'], $mimes) && in_array($extension, $allowedExts)) { 
+0

沒錯,你是right.But如果我想添加到默劇笨默那麼如何改變這種代碼,而啞劇$這裏。可能嗎? – user3617840

+1

是的,只需在'application/config/mimes.php'文件中添加新的mime,CI應該從那裏接收它們 –

0

:-) 我知道它已經2年,你既然問這個問題,但 仍然存在一些問題與笨mimes.php文件的最新版本,甚至存在!

我經歷了大量的StackOverFlow答案和搜索大部分時間,並找到了答案! 如果有人仍然有這個問題,你應該訪問我的以下answer

最好的問候, Randika

相關問題