Drag And Drop File

by tekky

HTML

<div class="dndbox">Drag directory or file here.</div>
<div class="prompt"><button type="button">Upload</button></div>

CSS

.dndbox
{
    border: 1px black solid;
    text-align: center;
    height: 40px;
    width 200px;
}

.prompt
{
    display: none;
}

JavaScript

var dndbox = $(".dndbox")[0];

dndbox.addEventListener("dragenter", function(e) {
    e.stopPropagation();
    e.preventDefault();
},false);

dndbox.addEventListener("dragover", function(e) {
    e.stopPropagation();
    e.preventDefault();
},false);

dndbox.addEventListener("drop", function(e) {
    e.stopPropagation();
    e.preventDefault();
    
    var itemList = e.dataTransfer.items;
    
    var fp = [];
    
    var traverse = function(entry)
        {
            if (entry.isFile) {
                entry.file(function(file) {
                    var filepromise = new Promise(function(res, rej) {
                        res(file);
                    });
                    fp.push(filepromise);
                });
            } else if (entry.isDirectory){
                var dR = entry.createReader();
                dR.readEntries(function(entries) {
                    for(var i = 0; i < entries.length; i++)
                    {
                        traverse(entries[i]);
                    }
                });
            }
        }

        var collection = [];
        for(var i = 0; i < itemList.length; i++) {
            var e = itemList[i].webkitGetAsEntry();
            var tp = new Promise(function(r, rj) {
                traverse(e);
                r(fp);
            });
            collection.push(tp);
        }
        
        Promise.all(collection).then(function(ff) {
            $(".prompt").show();
            $(".prompt").on("click", function() {
                $(this).hide();
                ff.forEach(function(pa) {
                    pa.forEach(function(p){
                        p.then(function(f)
                        {
                            console.log(f);
                        });
                         
                    });
                });
            });
        });
},false);