CodeIgniter文件上传类,错误与do_upload

时间:2017-08-17 12:58:42

标签: php excel codeigniter phpexcel phpexcelreader

我想编写函数来将excel文件上传到sql db。 我有一个问题,因为$this->upload->do_upload('file')没有执行,我无法弄清楚原因。

这是我的控制器:

function import(){
    $this->breadcrumbs[] = array(
           "title" => "Import",
           "link" => "interview/import"
       );
    $this->template->load("interview_import", $this->breadcrumbs, $data);
}

function import_data() {         
    $this->load->library("form_validation");        
    $config = array(
        'upload_path' => FCPATH. 'upload/',
        'allowed_types' => 'xls'
        );
    $this->load->library('upload', $config);
    if($this->upload->do_upload('file')) {
        $data = $this->upload->data();
        @chmod($data['full_path'], 0777);
    }
    $this->load->library("Spreadsheet_Excel_Reader");
    $this->spreadsheet_excel_reader->setOutputEncoding('CP1251');

    $this->spreadsheet_excel_reader->read($data['full_path']);
    $sheets = $this->spreadsheet_excel_reader->sheets[0];
    error_reporting(E_ALL ^ E_NOTICE);

    $data_excel = array();
    for ($i = 2; $i <= $sheets[0]['numRows']; $i++) {
        if ($sheets['cells'][$i][1] == '') {
            break;
        }
        $data_excel[$i -1]['name'] = $sheets['cells'][$i][1];
        $data_excel[$i -1]['phone'] = $sheets['cells'][$i][2];
        $data_excel[$i -1]['address'] = $sheets['cells'][$i][3];

        /*for ($j = 1; $j <= $data->sheets[0]['numCols']; $j++) {
            echo "\"".$data->sheets[0]['cells'][$i][$j]."\",";
        }
    echo "\n";*/
    }
    echo '<pre>';
    print_r($data_excel);
    echo '</pre>';
    die();       
}

这是我的观点:

<?php    
      echo form_open_multipart('interview/import_data');
      echo form_upload('file');
      echo '<br/>';
      echo form_submit(null, 'Upload');
      echo form_close();
?>

你知道我做错了什么吗?

尝试上传时收到错误消息:

&GT;遇到PHP错误 严重性:注意 消息:未定义的变量:数据 文件名:controllers / Interview.php 行号:521 回溯: 文件:C:\ Users \ A66155193 \ Desktop \ xampp \ htdocs \ yitt \ application \ controllers \ Interview.php 行:521 功能:_error_handler 文件:C:\ Users \ A66155193 \ Desktop \ xampp \ htdocs \ yitt \ index.php 行:311 功能:require_once

显然if子句可以执行,因为:

  

未定义的变量:数据

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

如果do_upload的条件检查文件是否上传而不是错误

if($this->upload->do_upload('file')) {
    $data = $this->upload->data();
    @chmod($data['full_path'], 0777);
} else{
    $error = array('error' => $this->upload->display_errors());
    print_r($error);
}

你必须检查它,因为$ data变量在if语句中初始化,而在底部则表示取消定义变量。