如何在CodeIgniter中导入Excel文件并检查文件扩展名


How to import an Excel file in CodeIgniter with checking file extension?

我试图上传一个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');
    }
}

上传前如何检查文件扩展名?你能帮我吗?

本行

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

你正在检查扩展 mime类型都是正确的,但AFAIK excel mime不是file/xls ->我不知道你在哪里想到的

根据这个资源,Excel文件的mime类型应该是:

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)) {