【问题标题】:How to set or upload only CSV type in Codeigniter如何在 Codeigniter 中仅设置或上传 CSV 类型
【发布时间】:2015-12-13 21:13:33
【问题描述】:

我正在尝试将 CSV 导入 MYSQL 数据库。我跟着教程here

现在我收到一个错误

您尝试上传的文件类型不允许。

以下是我的控制器代码:

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;
        }
    }

回调函数是由 stackoverflow 上的用户建议的,他解决了同样的问题,但不知何故对我不起作用。我有一个用户表,我只想使用上传的 CSV 插入用户,但不知何故它不允许我上传 CSV。

这是图书馆

<?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);
        }    
    }

【问题讨论】:

标签: php mysql codeigniter csv


【解决方案1】:

添加 $config['allowed_types'] = 'csv';到你的 $config 数组。

更多帮助请查看https://ellislab.com/codeigniter/user-guide/libraries/file_uploading.html

还可以通过路径 application\config\mimes.php 上的文件更清楚地了解文件上传类型的 csv 数组支持

如果你真的想要,你可以更新这个数组......

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

【讨论】:

  • 嗨,我保留了这个,但不好,它总是显示错误,也许我的其他部分代码有问题
  • 使用 Print_r($_FILES); 检查文件详细信息检查文件类型是否属于 csv 数组。
  • 我应该在哪里做这个??
  • 先替换'|'到 |在你初始化的 $config['allowed_types']
  • 在语句 $this->load->library('upload', $config); 后使用 print_r;
猜你喜欢
  • 2015-01-27
  • 1970-01-01
  • 1970-01-01
  • 2021-11-27
  • 2015-06-04
  • 2013-05-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多