Skip to content

Instantly share code, notes, and snippets.

@goldenflower
Created July 21, 2016 07:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save goldenflower/791edca6ded5677987ad6252c52468ca to your computer and use it in GitHub Desktop.
Save goldenflower/791edca6ded5677987ad6252c52468ca to your computer and use it in GitHub Desktop.
L.Micello.UploadManager= L.Class.extend({
options: {
id: '',
callback: '',
encapsulation: "",
format: ["csv"],
debug: false
},
initialize: function (element, options) {
this.element = element;
this.divid = options.id ;
this.callback = options.callback;
this.encapsulation = options.encapsulation;
this.format = options.format;
this.debug = options.debug;
return this;
// class constructor
},
loadForm: function () {
if (window.File && window.FileReader && window.FileList && window.Blob) {
var maindiv = this.element;
maindiv.id = this.divid;
maindiv.style.width = '100%';
maindiv.style.height = '100%';
maindiv.style.backgroundColor = 'rgb(0,0,0)';
maindiv.style.backgroundColor = 'rgba(0,0,0,0.4)';
// maindiv.style.border = this.getBorder();
maindiv.style.zIndex = 1000;
maindiv.style.left = '0px';
maindiv.style.top = '0px';
maindiv.style.display = 'block';
maindiv.style.position = 'fixed';
maindiv.style.overflow = 'auto';
var modalDiv = L.DomUtil.create('div','', maindiv);
modalDiv.id = 'modaldiv';
modalDiv.style.margin = '15% auto';
modalDiv.style.width = "600px";
modalDiv.style.height = "400px";
modalDiv.style.backgroundColor = "#ffffff";
modalDiv.style.border = "1px solid #C8C8C8";
var pcommon = L.DomUtil.create('p','', modalDiv);
pcommon.id = "pcomon";
pcommon.style.border = '0px';
pcommon.style.textAlign = 'center';
var divdrag = L.DomUtil.create('div','', pcommon);
divdrag.id ="drop_zone";
divdrag.style.width = "600px";
divdrag.style.height = "400px";
divdrag.style.textAlign = 'center';
var pcont2 = L.DomUtil.create('p','', divdrag);
pcont2.innerHTML = '<input type="file" display="none" id="files" name="files[]" multiple />';
pcont2.id = "pcont2";
pcont2.style.display = "none";
var filelbl = L.DomUtil.create('label','', divdrag);
filelbl.innerHTML = '<span id="choosefile" style="cursor:pointer;display:inline-block; font-weight: bold; color:#6FABE3;">Choose a file </span> <span style="font-weight: bold; color:#D4D2D2;"> <em> or</em> Drag it here</span>';
filelbl.id = "lblfile";
filelbl.style.display = "inline-block";
filelbl.style.fontSize = "20px";
filelbl.style.fontFamily = "sans-serif";
filelbl.style.textAlign = "canter";
filelbl.style.marginTop = "25%";
var pcancel = L.DomUtil.create('p','', divdrag);
pcancel.innerHTML = '<br><br><span style="cursor:pointer; text-decoration:underline; font-size:16px; color:#D4D2D2;"> Cancel </span>';
pcancel.id = "pcont1";
pcancel.title = "Click here to close.";
pcancel.style.border = '0px';
pcancel.style.textAlign = 'center';
pcancel.style.fontFamily = 'sans-serif';
var output = L.DomUtil.create('list','output', divdrag);
output.id = "list";
var progress = L.DomUtil.create('div','percent', divdrag);
progress.id ="progress_bar";
L.DomUtil.get('choosefile').addEventListener('click', this.clickFile, false);
L.DomEvent.on(pcancel, "click", function() {
maindiv.style.display = 'none';
L.DomUtil.remove(maindiv);
})
var that = this;
L.DomUtil.get('files').addEventListener('change', function(e){
var type="upload";
var retData = that.handleFileSelect(e, type, that);
// that.callback(retData);
} , false);
// Setup the dnd listeners.
L.DomEvent.addListener(divdrag, 'dragover', this.handleDragOver);
L.DomEvent.addListener(divdrag, 'drop', function(e){
var type="drag";
that.callback(that.handleFileSelect(e, type, that));
});
return maindiv ;
} else {
alert('The File APIs are not fully supported in this browser.');
}
},
clickFile: function (evt) {
L.DomUtil.get("files").click();
},
handleFileSelect: function (evt, type, that) {
var output = {};
var reader = new FileReader();
if(type == 'drag'){ //drag and drop
evt.stopPropagation();
evt.preventDefault();
var file = evt.dataTransfer.files[0];
}else{ //upload button
var file = evt.target.files[0];
}
var filename = file.name;
var validFile = true;
if(!file.type.match('text/'+that.format)) {
output.msg = file.name + " is not a valid file.";
validFile = false;
if(that.debug == true){ //if debug mode is true
L.DomUtil.get("list").innerHTML = output.msg;
}
that.callback(output);
}
if(validFile){
reader.onload = function (evt) {
L.DomUtil.get("progress_bar").innerHTML = 'File upload in progress.';
if(that.format == 'csv' && that.encapsulation == '"'){
var rows = evt.target.result;
output.file = file.name;
var filtered = that.csvToArray(rows, ',');
output.header = filtered[0];
filtered.shift();
output.data =filtered;
output.success = 'true';
if(that.debug == true){ //if debug mode is true
theData = JSON.stringify(output);
L.DomUtil.get("list").innerHTML = theData;
}
L.DomUtil.get("progress_bar").innerHTML = 'Completed.';
that.callback(output); //return output
}
}
reader.readAsText(file);
}else {
output.msg = "Failed to load file";
output.success = 'false';
that.callback(output);
}
reader.onerror = function (evt) {
if(evt.target.error.name == "NotReadableError") {
output.msg = "Canno't read file !";
that.callback(output);
}
}
},
handleDragOver: function(evt) {
evt.stopPropagation();
evt.preventDefault();
evt.dataTransfer.dropEffect = 'copy'; // Explicitly show this is a copy.
},
csvToArray: function( strData, strDelimiter ){
// Check to see if the delimiter is defined. If not,
// then default to comma.
strDelimiter = (strDelimiter || ",");
// Create a regular expression to parse the CSV values.
var objPattern = new RegExp(
(
// Delimiters.
"(\\" + strDelimiter + "|\\r?\\n|\\r|^)" +
// Quoted fields.
"(?:\"([^\"]*(?:\"\"[^\"]*)*)\"|" +
// Standard fields.
"([^\"\\" + strDelimiter + "\\r\\n]*))"
),
"gi"
);
// Create an array to hold our data. Give the array
// a default empty first row.
var arrData = [[]];
// Create an array to hold our individual pattern
// matching groups.
var arrMatches = null;
// Keep looping over the regular expression matches
// until we can no longer find a match.
while (arrMatches = objPattern.exec( strData )){
// Get the delimiter that was found.
var strMatchedDelimiter = arrMatches[ 1 ];
// Check to see if the given delimiter has a length
// (is not the start of string) and if it matches
// field delimiter. If id does not, then we know
// that this delimiter is a row delimiter.
if (
strMatchedDelimiter.length &&
strMatchedDelimiter !== strDelimiter
){
// Since we have reached a new row of data,
// add an empty row to our data array.
arrData.push( [] );
}
var strMatchedValue;
// Now that we have our delimiter out of the way,
// let's check to see which kind of value we
// captured (quoted or unquoted).
if (arrMatches[ 2 ]){
// We found a quoted value. When we capture
// this value, unescape any double quotes.
strMatchedValue = arrMatches[ 2 ].replace(
new RegExp( "\"\"", "g" ),
"\""
);
} else {
// We found a non-quoted value.
strMatchedValue = arrMatches[ 3 ];
}
// Now that we have our value string, let's add
// it to the data array.
arrData[ arrData.length - 1 ].push( strMatchedValue );
}
// Return the parsed data.
return( arrData );
}
});
L.micello.uploadmanager = function (element, options) {
return new L.Micello.UploadManager(element, options);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment