I've developed a method for file uploading using AJAX technology (pure JavaScript) in CodeIgniter.
Here's how it works:
1- I created a script.js file to manage the AJAX/JavaScript upload process.
2- I implemented a controller in CodeIgniter to handle requests from AJAX for file uploads.
3- I built a simple HTML page.
ISSUE: After clicking the upload button, nothing seems to happen! No errors are displayed. I suspect there's a data transfer issue between JavaScript and PHP. A similar code worked successfully in a regular PHP page.
Here are the files:
This is the JavaScript code:
// JavaScript Document
var doUpload = function(event){
// variables used within this function
var progressBar = document.getElementById('progressBar');
event.preventDefault(); // stop default action of element
event.stopPropagation();
// get the file-input id
var fileId = document.getElementById('file');
// create object to hold key/value pairs to be sent via ajax.send
var formObj = new FormData();
// append selected file to data object
formObj.append('file', fileId.files[0]);
// variable to check in the PHP script (controller if CodeIgniter is used)
formObj.append('error-check', true);
formObj.append('finish-check', true);
// create the AJAX request object
var ajaxReq = new XMLHttpRequest();
// PROGRESS OF THE FILE /////////////////////////////////////////////
// function to display progress during file upload
ajaxReq.upload.addEventListener('progress', function(event){
console.log('this is a very good.');
// get file load percentage
var percent = event.loaded / event.total;
if(event.lengthComputable) // if file is inserted and ready to upload
{
if(progressBar.hasChildNodes()) // clear div container for new progress display
{
progressBar.removeChild(progressBar.firsChild);
}
progressBar.appendChild(document.createTextNode('Progress So Far: '+percent*100+' %'));
}
// END OF PROGRESS OF THE FILE /////////////////////////////////////////////
// LOAD OF THE FILE /////////////////////////////////////////////
ajaxReq.upload.addEventListener('load', function(event){
progressBar.appendChild(document.createTextNode(" Completed!"));
});
// END OF LOAD OF THE FILE /////////////////////////////////////////////
// ERROR OF THE FILE /////////////////////////////////////////////
ajaxReq.upload.addEventListener('error', function(event){
progressBar.removeChild();
progressBar.appendChild(document.createTextNode("Failed to Upload the File."));
});
// END OF THE ERROR OF THE FILE /////////////////////////////////////////////
// JSON
// OPEN THE AJAX REQUEST
ajaxReq.open('POST', 'upload/uploader');
// Set the header of the POST request
ajaxReq.setRequestHeader('Cache-Control', 'no-cache');
// send the file. remember, we shoud pass a formData object as an argument to the ajaxRequest.send();
ajaxReq.send(formObj);
});
}
window.addEventListener('load', function(event)
{
// get the submit id
var submitButton = document.getElementById('submit');
submitButton.addEventListener('click', doUpload);
});
This is the PHP Controller in CodeIgniter:
<?php
class Upload extends CI_Controller
{
function index()
{
$this->load->view('pages/form');
}
function uploader ()
{
// define required settings for upload library
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png|doc|txt';
$config['max_size'] = 1024 * 8;
$config['encrypt_name'] = TRUE;
// load the upload library
$this->load->library('upload', $config);
if(!$this->upload->do_upload('file'))
{
$data['error'] = $this->upload->display_errors();
//$this->load->view('pages/form', $data);
json_encode($data['error']);
}
else
{
$data['uploaded'] = $this->upload->data();
//$this->load->view('pages/form', $data);
}
}
}
This is the HTML code:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Upload Form With Ajax</title>
<script src="<?php echo base_url(); ?>js/script.js" type='text/javascript'></script>
</head>
<body>
<div id='error' style='color: red;height: 40px; width: 200px;'>
<?php
if(!empty($error)){echo $error; }
?>
</div>
<form id='form' name='form' enctype="multipart/form-data" >
<input type='file' name='file' id='file'/>
<input type='submit' name='submit' id='submit' value='Upload File' />
</form>
<div style='height: 200px; width: 300px; color: red; padding: 10px; background-color: #CCC;' id='progressBar'></div>
</body>
</html>