douqiaotong8682 2015-09-17 05:03
浏览 34
已采纳

如何在Codeigniter中仅设置或上传CSV类型

I am trying to import a CSV into MYSQL database. I followed a tutorial here

Now i am getting an error that

The filetype you are attempting to upload is not allowed.

Below is my code for Controller :

function importcsv() {
    $data['addressbook'] = $this->csv_model->get_addressbook();
    $data['error'] = '';    //initialize image upload error array to empty

    $config['upload_path'] = './uploads/';
    $config['allowed_types'] = 'text/x-comma-separated-values'|'text/comma-separated-values'|'application/octet-stream'| 'application/vnd.ms-excel'|'application/x-csv'|'text/x-csv'|'text/csv'|'application/csv'|'application/excel'|'application/vnd.msexcel'|'text/plain';
    $config['max_size'] = '1000';

    $this->load->library('upload', $config);


    // If upload failed, display error
    if (!$this->upload->do_upload()) {
        $data['error'] = $this->upload->display_errors();

        $this->load->view('csvindex', $data);
    } else {
        $file_data = $this->upload->data();
        $file_path =  './uploads/'.$file_data['file_name'];

        if ($this->csvimport->get_array($file_path)) {
            $csv_array = $this->csvimport->get_array($file_path);
            foreach ($csv_array as $row) {
                $insert_data = array(
                    'firstname'=>$row['firstname'],
                    'lastname'=>$row['lastname'],
                    'phone'=>$row['phone'],
                    'email'=>$row['email'],
                );
                $this->csv_model->insert_csv($insert_data);
            }
            $this->session->set_flashdata('success', 'Csv Data Imported Succesfully');
            redirect(base_url().'csv');
            //echo "<pre>"; print_r($insert_data);
        } else 
            $data['error'] = "Error occured";
            $this->load->view('csvindex', $data);
        }

    } 

    public function chk_attachment() // callback validation for check the attachment extension
    {
        $file_type = array('.csv');
        if(!empty($_FILES['uploaded_file']['name']))
        {
            $ext = strtolower(strrchr($_FILES['uploaded_file']['name'],"."));
            if(in_array($ext,$ext_array))
            {
                return true;
            }
            else
            {
                $this->form_validation->set_message('chk_attachment','Attachment allowed only csv');
                return false;
            }
        }
        {
           $this->form_validation->set_message('chk_attachment','image field is required');
                return false;
        }
    }

The call back function was suggested by a user on stackoverflow who had same issue solved, but somehow didn't work for me. I have a users table and i just want to insert users using the uploaded CSV but somehow its not allowing me to upload a CSV.

This is the Library

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); 


    /**
     * CodeIgniter CSV Import Class
     *
     * This library will help import a CSV file into
     * an associative array.
     * 
     * This library treats the first row of a CSV file
     * as a column header row.
     * 
     *
     * @package         CodeIgniter
     * @subpackage      Libraries
     * @category        Libraries
     * @author          Brad Stinson
     */

    class Csvimport {

        private $filepath = "";
        private $handle = "";
        private $column_headers = "";

       /**
         * Function that parses a CSV file and returns results
         * as an array.
         *
         * @access  public
         * @param   filepath        string  Location of the CSV file
         * @param   column_headers  array   Alternate values that will be used for array keys instead of first line of CSV
         * @param   detect_line_endings  boolean  When true sets the php INI settings to allow script to detect line endings. Needed for CSV files created on Macs.
         * @return  array
         */
        public function get_array($filepath='', $column_headers='', $detect_line_endings=FALSE)
        {
            // If true, auto detect row endings
            if($detect_line_endings){
                ini_set("auto_detect_line_endings", TRUE);
            }

            // If file exists, set filepath
            if(file_exists($filepath))
            {
                $this->_set_filepath($filepath);
            }
            else
            {
                return FALSE;            
            }

            // If column headers provided, set them
            $this->_set_column_headers($column_headers);

            // Open the CSV for reading
            $this->_get_handle();

            $row = 0;

            while (($data = fgetcsv($this->handle, 0, ",")) !== FALSE) 
            {   
                // If first row, parse for column_headers
                if($row == 0)
                {
                    // If column_headers already provided, use them
                    if($this->column_headers)
                    {
                        foreach ($this->column_headers as $key => $value)
                        {
                            $column_headers[$key] = trim($value);
                        }
                    }
                    else // Parse first row for column_headers to use
                    {
                        foreach ($data as $key => $value)
                        {
                            $column_headers[$key] = trim($value);
                        }                
                    }          
                }
                else
                {
                    $new_row = $row - 1; // needed so that the returned array starts at 0 instead of 1
                    foreach($column_headers as $key => $value) // assumes there are as many columns as their are title columns
                    {
                        $result[$new_row][$value] = trim($data[$key]);
                    }
                }
                $row++;
            }

            $this->_close_csv();

            return $result;
        }

       /**
         * Sets the filepath of a given CSV file
         *
         * @access  private
         * @param   filepath    string  Location of the CSV file
         * @return  void
         */
        private function _set_filepath($filepath)
        {
            $this->filepath = $filepath;
        }

       /**
         * Sets the alternate column headers that will be used when creating the array
         *
         * @access  private
         * @param   column_headers  array   Alternate column_headers that will be used instead of first line of CSV
         * @return  void
         */
        private function _set_column_headers($column_headers='')
        {
            if(is_array($column_headers) && !empty($column_headers))
            {
                $this->column_headers = $column_headers;
            }
        }

       /**
         * Opens the CSV file for parsing
         *
         * @access  private
         * @return  void
         */
        private function _get_handle()
        {
            $this->handle = fopen($this->filepath, "r");
        }

       /**
         * Closes the CSV file when complete
         *
         * @access  private
         * @return  array
         */
        private function _close_csv()
        {
            fclose($this->handle);
        }    
    }
  • 写回答

1条回答 默认 最新

  • dongliechuich10319 2015-09-17 05:12
    关注

    Add $config['allowed_types'] = 'csv'; to your $config array.

    for more help check https://ellislab.com/codeigniter/user-guide/libraries/file_uploading.html

    Also go through the file on path application\config\mimes.php for more clear understanding about csv array support on file upload type

    You can update this array if you really want...

    'csv'   =>  array('text/x-comma-separated-values', 'text/comma-separated-values', 'application/octet-stream', 'application/vnd.ms-excel', 'application/x-csv', 'text/x-csv', 'text/csv', 'application/csv', 'application/excel', 'application/vnd.msexcel') 
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 求快手直播间榜单匿名采集ID用户名简单能学会的
  • ¥15 DS18B20内部ADC模数转换器
  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历