I'm looking for a way to drag&drop a json file into chrome and extract it's info.
You can use a combination of HTML5 Drag & Drop and FileReader
API to read the file:
var dnd = new DnDFileController('body', function(files) {
var f = files[0];
if (!f.type.match('application/json')) {
alert('Not a JSON file!');
}
var reader = new FileReader();
reader.onloadend = function(e) {
var result = JSON.parse(this.result);
console.log(result);
};
reader.readAsText(f);
});
DnDFileController
is from http://html5-demos.appspot.com/static/filesystem/filer.js/demos/js/dnd.js and just sets up the correct DnD event listeners on the element you pass in as the selector.
See http://jsbin.com/oqosav/2/edit
Here's minimal working code that is self-contained, without external dependencies:
function dropJSON(targetEl, callback) {
// disable default drag & drop functionality
targetEl.addEventListener('dragenter', function(e){ e.preventDefault(); });
targetEl.addEventListener('dragover', function(e){ e.preventDefault(); });
targetEl.addEventListener('drop', function(event) {
var reader = new FileReader();
reader.onloadend = function() {
var data = JSON.parse(this.result);
callback(data);
};
reader.readAsText(event.dataTransfer.files[0]);
event.preventDefault();
});
}
dropJSON(
document.getElementById("dropTarget"),
function(data) {
// dropped - do something with data
console.log(data);
}
);
The code doesn't contain any sanity checks or error handling.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With