How to upload file with ci.


Before you coding with ci you have to create a direct folder to uploads store file. in ci root directory.


View :

<?php 
 echo form_open_multipart('items/add_new_item',array('name'=>'sentMessage','id'=>'contactForm')); ?>
    <div class="row">
        <div class="col-md-12">
            <div class="form-group" style="color: #fff;">
                   <input  name="image" type="file">                                        
           </div>
        </div>
        <div class="clearfix"></div>
        <div class="col-lg-12 text-center">
            <div id="success"></div>
            <button type="submit" class="btn btn-success">Save</button>
            <button type="submit" class="btn btn-danger">Cancel</button>
        </div>
    </div>
</form>

Controller :

class items extends CI_Controller {

    public function __construct()
    {
        parent::__construct();
       
        $this->load->model('items_model');
    }
 
    public function add_new_item()
    {
        //set preferences
        $config['upload_path'] = './uploads/'; // folder name
        $config['allowed_types'] = '*';
        $config['max_size'] = '10000000';
       
        //load library of file upload
        $this->load->library('upload', $config);
       
        //copy file into folder
        if(!$this->upload->do_upload('image')) // input type name
        {
            $file = "";
           
        }else{
           
            $upload_data = $this->upload->data();
            $file = $upload_data['file_name'];
           
        }
       
        $data = array(
             'image' => $file
        );
       
        //Save to db
        $this->items_model->add_new_item($data);
       
        redirect('items');

    }
 }
Model:

    public function add_new_item($data)
    {
        return $this->db->insert('tb_items', $data);
    }

Share this

Related Posts

Previous
Next Post »

Newest questions tagged codeigniter - Stack Overflow