Drag and drop mult-file uploads (Part I)

This is the first in a two part series about native browser based multifile drag and drop uploads.

Last year when I was working on zugunroute.com I needed to make uploading multiple files from GPS receivers easy. I was delighted to find out that multifile uploads with drag and drop are well supported in modern browsers. Support in the major browsers is there. Firefox, Chrome, Safari, Opera and IE 10 onward all support the posting of multiple files via HTTP.

I’ll start with a brief explanation of how single file uploads work. From there we’ll show how to modify your html and server side code for multiple file uploads. Finally, in part II, we’ll cover the client side approach to handling drag and drop events to invoke the upload.

Continue reading

Drag and drop mult-file uploads (Part II)

Part I describes single and multi-file uploads. This post adds the ability to accept drag and drop uploads.

Place your form inside an appropriately styled div. Call this the drop area. We then attach a few event handlers. One to block the event so that the page is not replaced with the droppped file. The next to handle the drop event in your drop area.

The HTML from Part I expanded to have a #drop_area:

<div id="drop_area">
  <form enctype="multipart/form-data" method="POST">
    <input id="file" multiple="" name="pic[]" type="file">
    <input name="Upload" type="Submit">
  </form>
</div>

JavaScript/ jQuery:

  $(function() {
    document.addEventListener("dragover", function(event) {
      event.preventDefault()
    }, true)

    $('#drop_area').on('drop', function(e) {
      e.preventDefault()
      e.stopPropagation()

      var files = e.originalEvent.dataTransfer.files
      $('#file')[0].files = files
      $('form').submit()

      return false
    })
  })

addEventListener() is used because I could not find a method of blocking the event at the page/ document level using jQuery.

The drop handler is attached to the #drop_area tag. It fetches the FileList from the event and assigns it to the file field.