Skip to content

Instantly share code, notes, and snippets.

@joshbeckman
Created December 9, 2013 06:00
Show Gist options
  • Save joshbeckman/7867934 to your computer and use it in GitHub Desktop.
Save joshbeckman/7867934 to your computer and use it in GitHub Desktop.
Handle drag-n-drop JSON file upload and parsing with javascript.
if (window.File && window.FileReader && window.FileList && window.Blob) {
// Great success!
function handleJSONDrop(evt) {
evt.stopPropagation();
evt.preventDefault();
var files = evt.dataTransfer.files;
// Loop through the FileList and read
for (var i = 0, f; f = files[i]; i++) {
// Only process json files.
if (!f.type.match('application/json')) {
continue;
}
var reader = new FileReader();
// Closure to capture the file information.
reader.onload = (function(theFile) {
return function(e) {
p = JSON.parse(e.target.result);
var span = document.createElement('span');
span.innerHTML = p[Object.keys(p)[0]];
document.getElementById('div').insertBefore(span, null);
};
})(f);
reader.readAsText(f);
}
}
function handleDragOver(evt) {
evt.stopPropagation();
evt.preventDefault();
evt.dataTransfer.dropEffect = 'copy'; // Explicitly show this is a copy.
}
// Setup the dnd listeners.
var dropZone = document.getElementsByTagName('body')[0];
dropZone.addEventListener('dragover', handleDragOver, false);
dropZone.addEventListener('drop', handleJSONDrop, false);
} else {
alert('The File APIs are not fully supported in this browser.');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment