【问题标题】:How to import an Excel file in CodeIgniter with checking file extension?如何通过检查文件扩展名在 CodeIgniter 中导入 Excel 文件?
【发布时间】:2014-06-28 16:26:10
【问题描述】:

我正在尝试在我的上传目录中上传一个 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');
    }
}

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

【问题讨论】:

    标签: php excel codeigniter


    【解决方案1】:

    在这一行

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

    您正在检查两个扩展 AND mime 类型是否正确,但 AFAIK excel MIME 不是 file/xls -> 我不知道您是从哪里想到的。

    根据this resource,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)) {
    

    【讨论】:

    • 没错,你是对的。但是如果我想将 mime 添加到 codeigniter mime 那么如何在没有 $mimes 的情况下更改此代码。有可能吗?
    • 是的,只需在 application/config/mimes.php 文件中添加新的 mime,CI 就会从那里获取它们
    猜你喜欢
    • 2013-02-27
    • 2017-03-21
    • 1970-01-01
    • 2011-08-19
    • 1970-01-01
    • 2014-10-30
    • 2012-06-11
    • 1970-01-01
    • 2012-06-12
    相关资源
    最近更新 更多