0

I'm quite new to the codeigniter library and function. Recently i had a form that had a few dynamic input field to be submit and insert into database for recording purpose.

The image upload file field was dynamically created if user click "+" button, and i was using array name as the name for the input field. However when i trying to call the controller to upload the file or insert with the array field name, it keep prompted me 'You did not select a file to upload'.

If i change the image field's input name to only 'reg_photo' and the do upload field name to 'reg_photo' then everything working fine but that is not i wanted because i wanted to upload it based on the dynamic input array.

I did try to look around the solution at stackoverflow and google but after i try and none of it could help me.

Here are my Controller to do the upload :

 //Upload Picture Configuration
        $config['upload_path']          = './uploads/profile_picture/';
        $config['allowed_types']        = 'gif|jpg|png';
        $config['max_size']             = 2048;
        $config['max_width']            = 1920;
        $config['max_height']           = 1080;
        $this->load->library('upload', $config);

        //Check and get the Areas list
        $areaList = $this->input->post('areas', true);
        $finalSeparator = $areaList;
        $resultArea = "";
        foreach ($finalSeparator as $i => $a) {
            if (next($finalSeparator )) {
                $resultArea .= $a.','; // Add comma for all elements instead of last
            }
            else
            {
                $resultArea .= $a;
            }
        }


        if ($this->input->post('reg_name')) { // returns false if no property

            //Get Last Inserted District ID
            $district = "";
            $failedUploadNameList = "";
            $photoPath = "";
            $data = array(
                'district_code' => $this->input->post('reg_district_2', true),
                'district_country' => '',
            );
            $this->db->set('district_registered_date', 'NOW()', FALSE); //Submit current date time
            if($this->Registerlanguage_admin_model->register_district($data))
            {
                $district = $this->db->insert_id(); //Last Get ID

                $name = $this->input->post('reg_name', true);
                $year1 = $this->input->post('reg_year1', true);
                $year2 = $this->input->post('reg_year2', true);
                $nickname = $this->input->post('reg_nickname', true);
                $photo = $this->input->post('reg_photo', true);

                foreach ($name as $i => $a) { // need index to match other properties

                    //Check to whether can upload image or not
                    if ( ! $this->upload->do_upload($photo[$i]))
                    {
                        $error = array('error' => $this->upload->display_errors());
                        foreach($error as $q)
                        {
                            $failedUploadNameList .= $q;
                        }
                    }
                    else
                    {
                        $data = array('upload_data' => $this->upload->data('file_name'));

                        foreach($data as $a)
                        {
                            $photoPath = $config['upload_path'].$a;
                        }
                    }
                    $data = array(
                        'area_district_id' => $district,
                        'area_name' => $resultArea,
                        'area_language' =>  $this->input->post('reg_language', true),
                        'area_year_1' => isset($year1[$i]) ? $year1[$i] : '',
                        'area_year_2' => isset($year2[$i]) ? $year2[$i] : '',
                        'area_leader_name' => isset($name[$i]) ? $name[$i] : '',
                        'area_leader_nickname' => isset($nickname[$i]) ? $nickname[$i] : '',
                        'area_leader_photo' => $photoPath
                    );
                    $this->db->set('area_registered_date', 'NOW()', FALSE); //Submit current date time
                    if (!$this->Registerlanguage_admin_model->register_area($data)) {
                        // quit if insert fails - adjust accordingly
                        $this->session->set_flashdata('msg','<div class="alert alert-danger text-center">Oops! Error.  Please try again later!!!</div>');
                        redirect('index.php/language_admin/index');
                    }
                }
            }
            else{
                // don't redirect inside the loop
                $this->session->set_flashdata('msg','<div class="alert alert-danger text-center">Oops! Error.  Please try again later!!!</div>');
                redirect('index.php/language_admin/index');
            }

            //Redirect back once all successfully insert
            $this->session->set_flashdata('msg','<div class="alert alert-success text-center">You are Insert Successfully!</div>'.$failedUploadNameList);
            redirect('index.php/language_admin/index');
        }
        else{

            // don't redirect inside the loop
            $this->session->set_flashdata('msg','<div class="alert alert-danger text-center">Oops! Error.  Please try again later!!!</div>');
            redirect('index.php/language_admin/index');
        }

Here are my view code :

 <?php $attributes = array("name" => "registerdistrictform");
                            echo form_open_multipart("index.php/registerlanguage_admin/registerDistrict", $attributes);?>
                            <div class="panel panel-default">
                                <div class="panel panel-info">
                                    <div class="panel-body  panel-group">
                                        <div class="form-group">
                                            <input class="form-control" name="reg_language" type="hidden" value="Japanese" />
                                            <label for="concept" class="col-sm-3 control-label">District :</label>
                                            <div class="col-sm-9">
                                                <input class="form-control" name="reg_district_1" placeholder="Ex : District 3500" type="text" value="<?php echo set_value('reg_district_1'); ?>" required/>
                                                <span class="text-danger"><?php echo form_error('reg_district_1'); ?></span><br/>
                                                <input class="form-control" name="reg_district_2" placeholder="Ex : 3500" type="text" value="<?php echo set_value('reg_district_2'); ?>" required/>
                                                <span class="text-danger"><?php echo form_error('reg_district_2'); ?></span><br/>
                                            </div>
                                        </div>
                                        <div class="form-group">
                                            <label for="concept" class="col-sm-3 control-label">Area :</label>
                                            <div id="areaContainer">
                                                <div class="col-sm-6">
                                                    Area Record #0<input class="form-control" name="areas[]" placeholder="Your Language" type="text" value="" required/>
                                                </div>
                                                <div class="col-sm-3">
                                                    <a href="#" class="btn btn-primary" id="addArea">+</a><br/>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <div id = "profileContainer">
                                    <div class="panel panel-danger">
                                        <div class="panel-heading">Profile #0</div>
                                        <div class="panel-body  panel-group">
                                            <div class="form-group">
                                                <label for="concept" class="col-sm-3 control-label">Years :</label>
                                                <div class="col-sm-4">
                                                    <input class="form-control" name="reg_year1[]" placeholder="2015" type="text" value="" required/>
                                                </div>
                                                <div class="col-sm-1">
                                                    <i class="fa fa-arrow-right" aria-hidden="true" ></i>
                                                </div>
                                                <div class="col-sm-4">
                                                    <input class="form-control" name="reg_year2[]" placeholder="2017" type="text" value="" required/><br/>
                                                </div>
                                            </div>
                                            <div class="form-group">
                                                <label for="concept" class="col-sm-12 control-label"><u>District Governer</u></label><br/>
                                                <label for="concept" class="col-sm-3 control-label">Name :</label>
                                                <div class="col-sm-9">
                                                    <input class="form-control" name="reg_name[]" placeholder="Your Language" type="text" required/><br/>
                                                </div>
                                                <label for="concept" class="col-sm-3 control-label">Nickname :</label>
                                                <div class="col-sm-9">
                                                    <input class="form-control" name="reg_nickname[]" placeholder="English" type="text" required/><br/>
                                                </div>
                                                <label for="concept" class="col-sm-3 control-label">Photo :</label>
                                                <div class="col-sm-9">
                                                    <input class="form-control" name="reg_photo[]" type="file" required/><br/>
                                                </div>
                                            </div>
                                            <div class="pull-right">
                                                <a href="#" class="btn btn-primary" id="addProfile">+</a>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <div class="panel-body  panel-group">
                                    <div class="form-group">
                                        <div class="col-sm-1 text-left">
                                            <button name="submit" type="submit" class="btn btn-info btn-lg" >Submit</button>
                                            <!--                <button name="cancel" type="reset" class="btn btn-info">Cancel</button>-->
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <?php echo form_close(); ?>
                        </div>

The 'reg_photo[]' are dynamically insert into HTML if user press the '+' button, so if i change to 'reg_photo' which is not dynamic anymore then it work, what should i do if i wanted to use the 'reg_photo[]' as a field name to upload my file? Please guide me through this. Thank! :)

10
  • $photo = $_FILES['reg_photo']; file should be accessed from $_FILES not form post value Commented Jun 9, 2017 at 5:12
  • @JYoThI Let me try it out, so the field name inside the do_upload still remain as $photo[$i] right? Commented Jun 9, 2017 at 5:13
  • yes of course @Marcus Commented Jun 9, 2017 at 5:14
  • @JYoThI still same prompted out 'You did not select a file to upload.' Commented Jun 9, 2017 at 5:15
  • first var_dump($_FILES['reg_photo']); exit; and know the file is posted to server or not Commented Jun 9, 2017 at 5:16

2 Answers 2

2
/*
* Code above omitted purposely
* In your HTML form, your input[type=file] must be named *upl_files[]*
*/
/*
* Uploads multiple files creating a queue to fake multiple upload calls to
* $_FILE
*/
public function multiple_upload()
{
    $this->load->library('upload');
    $number_of_files_uploaded = count($_FILES['upl_files']['name']);
    // Faking upload calls to $_FILE
    for ($i = 0; $i < $number_of_files_uploaded; $i++){
        $_FILES['userfile']['name']     = $_FILES['upl_files']['name'][$i];
        $_FILES['userfile']['type']     = $_FILES['upl_files']['type'][$i];
        $_FILES['userfile']['tmp_name'] = $_FILES['upl_files']['tmp_name'][$i];
        $_FILES['userfile']['error']    = $_FILES['upl_files']['error'][$i];
        $_FILES['userfile']['size']     = $_FILES['upl_files']['size'][$i];
        $config = array(
            'file_name'     => <your ouw function to generate random names>,
            'allowed_types' => 'jpg|jpeg|png|gif',
            'max_size'      => 3000,
            'overwrite'     => FALSE,

            /* real path to upload folder ALWAYS */
            'upload_path'
            => $_SERVER['DOCUMENT_ROOT'] . '/path/to/upload/folder'
        );
        $this->upload->initialize($config);
        if ( ! $this->upload->do_upload()) {
            $error = array('error' => $this->upload->display_errors());
            $this->load->view('upload_form', $error);
        }else {
            $final_files_data[] = $this->upload->data();
            // Continue processing the uploaded data
        }
    }
}

This Worked for me. reffer to this page this is not my code https://gist.github.com/zitoloco/1558423

Sign up to request clarification or add additional context in comments.

Comments

1

Try this code to upload image

     $directory = "./images/";
     $config['upload_path']   = $directory; 
     $config['encrypt_name'] = TRUE; 
     $config['allowed_types'] = 'gif|jpg|png|jpeg';
     if (!$this->upload->do_upload('mainimage'))
     {          
        $error = array('error' => $this->upload->display_errors()); 
        print_r($error);
     }
     else { 
        $data = array('upload_data' => $this->upload->data()); 
        print_r($data);
     }

And one other change is : Replace upload.php file. take latest verison upload.php file from system directory -> libraries directory -> upload.php. Copy new version upload.php file and replace in your project

Hope it will work properly.

12 Comments

but your code was only for single upload right? My code was fine with single upload, but not working if multiple upload
try to replace upload.php file
I'm currently using the latest codeigniter. Which upload.php do you mean
in system directory -> libraries directory -> upload.php.
this will not upload array files read the question then answer
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.