Upload Files using Ajax in Codeigniter

Codeigniter PHP

Hi world! My name is sooraj and  here i am going to teach  how to upload a file using ajax in codigniter. This tutorial will help you to learn about file upload functionality without loading the page. In this example the file can select using the browse button and can be automatically uploaded to the ‘uploads’ directory. The Controller will do the action for uploading the file and it will return a success or failure message back.  As a validation step I have added only to check if you have selected a file for uploading or not.

Step 1:
Create a folder under your root directory and named it as ‘uploads’

Step 2:
Now modify <root directory>/application/config/autoload.php file for auto-loading html, url, file, and form helpers

1
$autoload[‘helper’] = array(‘html’, ‘url’, ‘file’, ‘form’);

Step3: 
Create a controller file ajax.php under <root directory>/application/controllers with the following source code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
<?php
if (!defined(‘BASEPATH’))  exit(‘No direct script access allowed’);
/**
* Description of ajax upload
*
* @author http://soorajp.com

*/

class Ajax extends CI_Controller {
    function __construct() {
        parent::__construct();
    }
    function index() {
        $this->load->view(‘file_upload_ajax’, NULL);
    }
    function upload_file() {
        //upload file
        $config[‘upload_path’] = ‘uploads/’;
        $config[‘allowed_types’] = ‘*’;
        $config[‘max_filename’] = ‘255’;
        $config[‘encrypt_name’] = TRUE;
        $config[‘max_size’] = ‘1024’; //1 MB
        if (isset($_FILES[‘file’][‘name’])) {
            if (0 < $_FILES[‘file’][‘error’]) {
                echo ‘Error during file upload’ . $_FILES[‘file’][‘error’];
            } else {
                if (file_exists(‘uploads/’ . $_FILES[‘file’][‘name’])) {
                    echo ‘File already exists : uploads/’ . $_FILES[‘file’][‘name’];
                } else {
                    $this->load->library(‘upload’, $config);
                    if (!$this->upload->do_upload(‘file’)) {
                        echo $this->upload->display_errors();
                    } else {
                        echo ‘File successfully uploaded : uploads/’ . $_FILES[‘file’][‘name’];
                    }
                }
            }
        } else {
            echo ‘Please choose a file’;
        }
    }
}

 

Step 3. Create a view file file_upload_ajax.php under <root directory>/application/views

Step 4:
 If everything goes good then run the program.

Leave a Reply

Your email address will not be published. Required fields are marked *