How to upload files using ajax in codeigniter?

Member

by lew , in category: PHP Frameworks , 6 months ago

How to upload files using ajax in codeigniter?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by edmond_brakus , a month ago

@lew 

To upload files using AJAX in CodeIgniter, you can follow these steps:


Step 1: Create a form in your view file with an input field of type file for file upload and a button for submitting the form.

1
2
3
4
<form id="uploadForm" method="post" enctype="multipart/form-data">
    <input type="file" name="file" id="file">
    <button type="button" id="uploadButton">Upload File</button>
</form>


Step 2: Write an AJAX script to handle the file upload and update the form data.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
<script type="text/javascript">
    $(document).ready(function(){
        $('#uploadButton').click(function(){
            var form_data = new FormData();
            var file_data = $('#file').prop('files')[0];
            form_data.append('file', file_data);

            $.ajax({
                url: '<?php echo base_url("uploadFile"); ?>',
                type: 'post',
                data: form_data,
                contentType: false,
                processData: false,
                success: function(response){
                    alert(response);
                }
            });
        });
    });
</script>


Step 3: Create a controller method in CodeIgniter to handle the file upload.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
public function uploadFile(){
    $config['upload_path'] = './uploads/';
    $config['allowed_types'] = 'gif|jpg|png|jpeg';
    
    $this->load->library('upload', $config);
    
    if($this->upload->do_upload('file')){
        echo 'File uploaded successfully';
    }else{
        echo 'File upload failed';
    }
}


Step 4: Set up the routes in CodeIgniter to route the AJAX request to the controller method.

1
$route['uploadFile'] = 'YourController/uploadFile';


Now, when you select a file and click the "Upload File" button in the form, the file will be uploaded using AJAX in CodeIgniter.