Drag-and-drop file uploading without AJAX, synchronously in the foreground?

Although not really “synchronous” (JavaScript execution won’t actually halt), you can set the files selected by <input type="file"> programatically. In fact, such elements and dragging share their file backend implementation (File and FileList instances), so it’s really straight-forward. What’s more, due to both frontends using FileLists, dragging multiple files work just as seamlessly.

This works in Chrome (using jQuery): http://jsfiddle.net/qMmPr/.

$(document).on("dragover drop", function(e) {
    e.preventDefault();  // allow dropping and don't navigate to file on drop
}).on("drop", function(e) {
    $("input[type="file"]")
        .prop("files", e.originalEvent.dataTransfer.files)  // put files into element
        .closest("form")
          .submit();  // autosubmit as well
});

Leave a Comment