Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Drag & Drop Json into Chrome

I'm looking for a way to drag&drop a json file into chrome and extract it's info.

like image 709
itamarb Avatar asked Dec 16 '22 05:12

itamarb


2 Answers

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

like image 136
ebidel Avatar answered Dec 24 '22 04:12

ebidel


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.

like image 24
Florian Ledermann Avatar answered Dec 24 '22 03:12

Florian Ledermann