Created
December 9, 2013 06:00
-
-
Save joshbeckman/7867934 to your computer and use it in GitHub Desktop.
Handle drag-n-drop JSON file upload and parsing with javascript.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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