HTML:
<form id = "emailform" action = "admincsvupload" role="form" method="post" enctype="multipart/form-data">
<div class="form-group">
<label class="sr-only" for="csvfile">Upload CSV</label>
<input type="file" name = "csvfile" class="form-control" id="csvfile" placeholder="Select CSV file">
</div>
<button type="button" class="btn btn-success" id="btnLoad">Load</button>
<button type="submit" class="btn btn-success" id="btnSubmit" style="display:none">Upload Now!</button>
</form>
0%
Javascript:
// File load as HTMl n a table before actuly upload it on the server
function updateProgress(evt) {
// evt is an ProgressEvent.
if (evt.lengthComputable) {
var percentLoaded = Math.round((evt.loaded / evt.total) * 100);
// Increase the progress bar length.
if (percentLoaded < 100) {
progress.style.width = percentLoaded + '%';
progress.textContent = percentLoaded + '%';
}
}
}
function readBlob(opt_startByte, opt_stopByte) {
var progress = document.querySelector('.percent');
var files = document.getElementById('csvfile').files;
if (!files.length) {
alert('Please select a file!');
return;
}
var file = files[0];
var start = 0;
var stop = file.size - 1;
progress.style.width = '0%';
progress.textContent = '0%';
var reader = new FileReader();
//Reader progress
reader.onprogress = updateProgress;
// If we use onloadend, we need to check the readyState.
reader.onloadend = function (evt) {
if (evt.target.readyState == FileReader.DONE) { // DONE == 2
var data = evt.target.result;
var delimiter = ',';
var escape = '\n';
var rows = data.split(escape);
var tbl = document.createElement('table');
tbl.style.width = '100%';
//tbl.setAttribute('border', '1', "green");
tbl.className = "table table-hover table-condensed dataTable";
var tbdy = document.createElement('tbody');
for (index in rows) {
var tr = document.createElement('tr'); // creating new row
var items = rows[index].split(delimiter);
for (itemindex in items) {
var td = "";
if (index == 0) {
td = document.createElement('th');
} else {
td = document.createElement('td');
}
td.appendChild(document.createTextNode(items[itemindex])); // creating new cell
tr.appendChild(td); // add to current tr
}
tbdy.appendChild(tr); // add new row (tr) to table
}
tbl.appendChild(tbdy);
document.getElementById('byte_content').innerHTML=tbl;
}
};
// Progress Loading
reader.onloadstart = function(e) {
document.getElementById('progress_bar').className = 'loading';
};
reader.onload = function(e) {
// Ensure that the progress bar displays 100% at the end.
progress.style.width = '100%';
progress.textContent = '100%';
setTimeout("document.getElementById('progress_bar').className='';", 2000);
}
var blob = file.slice(start, stop + 1);
reader.readAsBinaryString(blob);
document.querySelector('#btnLoad').style.display = "none";
document.getElementById("btnSubmit").style.display = "block";
}
//Change event if user select a new file.
document.querySelector('#csvfile').addEventListener('change', function (evt) {
return readBlob();
}, false);