Drag and drop files and upload them using Ajax/Xhr2

Uploading files using XMLHttpRequest level 2 (XHR2)

This time, let us mash-up a couple of examples. Let’s combine the upload of files using XHR2, with progress monitoring (we worked on in the 3.2 lectures) with one of our drag and drop examples. To achieve this, we re-use the method called uploadAllFilesUsingAjax() and add a <progress> element to the drag and drop example.

example

Try this interactive example at JSBin (this example does not work on CodePen. We are using a fake remote server and it cancels the connection as soon as we try to connect):

example that uses drag'n'drop and a progress element for monitoring the ajax upload of the files

Source code extract (we omitted the CSS):

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4.    <style>
  5.      
  6.    </style>
  7.    
  8.      function dragLeaveHandler(event) {
  9.        console.log(“drag leave”);
  10.        // Set style of drop zone to default
  11.        event.target.classList.remove(‘draggedOver’);
  12.      }
  13.      function dragEnterHandler(event) {
  14.        console.log(“Drag enter”);
  15.        // Show some visual feedback
  16.        event.target.classList.add(‘draggedOver’);
  17.      }
  18.      function dragOverHandler(event) {
  19.        //console.log(“Drag over a droppable zone”);
  20.        // Do not propagate the event
  21.        event.stopPropagation();
  22.        // Prevent default behavior, in particular when we drop images
  23.        // or links
  24.        event.preventDefault();
  25.      }
  26.      function dropHandler(event) {
  27.        console.log(‘drop event’);
  28.        // Do not propagate the event
  29.        event.stopPropagation();
  30.        // Prevent default behavior, in particular when we drop images
  31.        // or links
  32.        event.preventDefault();
  33.        // reset the visual look of the drop zone to default
  34.        event.target.classList.remove(‘draggedOver’);
  35.        // get the files from the clipboard
  36.        var files = event.dataTransfer.files;
  37.        var filesLen = files.length;
  38.        var filenames = “”;
  39.        // iterate on the files, get details using the file API
  40.        // Display file names in a list.
  41.        for(var i = 0 ; i  filesLen ; i++) {
  42.           filenames += ‘\n’ + files[i].name;
  43.           // Create a li, set its value to a file name, add it to the ol
  44.           var li = document.createElement(‘li’);
  45.           li.textContent = files[i].name;
  46.           document.querySelector(“#droppedFiles”).appendChild(li);
  47.        }
  48.        console.log(files.length + ‘ file(s) have been dropped:\n’
  49.                                 + filenames);
  50.        uploadAllFilesUsingAjax(files);
  51.      }
  52.      function uploadAllFilesUsingAjax(files) {
  53.        var xhr = new XMLHttpRequest();
  54.        xhr.open(‘POST’, ‘upload.html’);
  55.        xhr.upload.onprogress = function(e) {
  56.           progress.value = e.loaded;
  57.           progress.max = e.total;
  58.        };
  59.        xhr.onload = function() {
  60.          alert(‘Upload complete!’);
  61.        };
  62.        var form = new FormData();
  63.        for(var i = 0 ; i  files.length ; i++) {
  64.           form.append(‘file’, files[i]);
  65.        }
  66.        // Send the Ajax request
  67.        xhr.send(form);
  68.      }
  69.   
  70. </head>
  71. <body>
  72. <h2>Drop your files here!</h2>
  73.  id=“droppableZone” ondragenter=dragEnterHandler(event)
  74.                          ondrop=dropHandler(event)
  75.                          ondragover=dragOverHandler(event)     
  76.                          ondragleave=dragLeaveHandler(event)>
  77.      Drop zone
  78.      
       id=“droppedFiles”>
  • <br/>
  •  Uploading progress: <progress id=“progress”></progress>
  • <body>
  • <html>
  • We have highlighted the interesting parts in the example!

    We build (line 75) an object of type FormData (this comes from the standard JavaScript DOM API level 2), we fill this object with the file contents (line 77), then we send the Ajax request (line 81), and monitor the upload progress (lines 66-69).

    Instead of uploading all the files at once, it might be interesting to upload one file at a time with visual feedback, such as: “uploading file MichaelJackson.jpg…..”. We will leave this exercise up to you.