Test HTTP Requests Tools Blog Learn Quizzes Smile API Log In / Sign Up
Test HTTP Requests Tools Blog Learn Quizzes Smile API Log In / Sign Up
« Return to the tutorials list
We have updated the website and our policies to make sure your privacy rights and security are respected.
Click here to learn more about the way our website handles your data.

Remove this message.

Simple Ajax Upload with Drag and Drop

Daniel Gheorghe Difficulty: 50 / 50 Tweet

This article is old. Be careful! It might contain outdated information.

stacked files

Today I will show you how to develop an Ajax upload script that works with drag and drop. For this project I am using plain JavaScript and I have no fallback mechanism for browsers that don't support these features... so you will have to deal with that yourselves.

For a full demo or if you only want to download the source code go here

Here's how it all works!

First we need to define the set of HTML elements that we will be using, an array that will hold data about the dragged files and custom functions (event listeners) for the "dragover", "dragleave" and "drop" events.

  
    <script>
      /*HTML Elements: */
      var filedrag = document.getElementById('filedrag');
      var previewarea = document.getElementById('previewarea');
      var uploader_form = document.getElementById('uploader_form');
      var uploadnow     = document.getElementById('uploadnow');
      /*Event listeners: */
      filedrag.addEventListener("dragover", FileIsOverElement, false);
      filedrag.addEventListener("dragleave", FileIsOverElement, false);
      filedrag.addEventListener("drop", FilesHaveBeenDropped, false);
      /*The files: */
      var thefiles = [];
    </script>
  

Now we need to write the two functions that handle our events: "FileIsOverElement" and "FilesHaveBeenDropped". First thing that needs to be done for all 3 events is to stop them from doing what they normally would: show the dragged file in the browser. To do that, use the stopPropagation() and preventDefault() methods.

Then, once the files have been droppped we put them in a "droppped" variable that reads the special "dataTransfer" or the "target.files" property of the drop event. Then we push the contents of the dropped array into "thefiles" which we defined at the beginning and we also display a preview of the files that will be uploaded.

  
    <script>
      function FileIsOverElement(e)
      {
        e.stopPropagation();
        e.preventDefault();
      }

      function FilesHaveBeenDropped(e)
      {
        e.stopPropagation();
        e.preventDefault();
        FileIsOverElement(e);
        var dropped = e.target.files || e.dataTransfer.files;
        for (var i = 0; i<dropped.length; i++)
        {
          thefiles.push(dropped[i]);
          var newfilepreview = document.createElement('p');
          newfilepreview.innerHTML = 'You are uploading ' + dropped[i].name;
          previewarea.appendChild(newfilepreview);
        }
      }
    </script>
  

Now we have our "file objects" so all we need to do is to send them to the server. After some initial validations, which you can extend as you please, we need to append every file to a FormData object, and then send it through Ajax as you would do with a simple input string. For those of you who don't know the FormData interface provides the tools to compile a set of key/value pairs to send over an XMLHttpRequest. FormData works with any form element, including file types and you can also add custom key, value pairs using the built in "Append" method.

  
    <script>
      uploader_form.onsubmit = function(event)
      {
        event.preventDefault();
        if(thefiles.length<=0) {alert('Drag a file'); return; }
        if(thefiles.length>3) {alert('I only allow 3 files at a time');return; }
        uploadnow.innerHTML = 'Uploading...';
        var formData = new FormData();
        for (var i = 0; i < thefiles.length; i++)
        {
          formData.append('myfiles[]', thefiles[i], thefiles[i].name);
        }
        var xhr = new XMLHttpRequest();
        xhr.open('POST', '', true);
        xhr.onload = function () {
          if (xhr.status === 200)
          {
            uploadnow.innerHTML = 'Upload';
            previewarea.innerHTML = 'You have uploaded these file types: ' + xhr.responseText;
          }
          else
            alert('An error occurred!');
        };
        xhr.send(formData);
      };
    </script>
  

Again, hope this has helped you understand how uploading through Ajax works. Now, if you prefer, you can use one of those plugins available on the internet, but at least now you understand what happens.

Special thanks go to The Mozilla Developer Network!

comments powered by Disqus