2014-05-11 91 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

相关问题