Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Drag and Drop File Uploading

I am using file uploading in my web application by using the <input type="file" /> html tag. My feature works well with choosing a file from the file chooser and submitting the file, however now I want to upload a file on drag and drop events i.e. the user drags a file from some location on his computer and when he drops it in a particular section in my web page, the file starts uploading.

Until now I managed to read the files from the drop event by

  function drop(evt)
    {
       evt.stopPropogation();
           evt.preventDefault();

       if (containsFiles(evt))
       {
        var files = evt.dataTransfer.files;
        var count = files.length;

        // Only call the handler if 1 or more files was dropped.
        if (count > 0)
            // upload files
        }
      }
    }

but how can I upload these files? I can't change the value of input type = file for security reasons. So what can I do to pass these files to my servlet?

like image 940
Bernice Avatar asked Jul 29 '13 15:07

Bernice


People also ask

How do I enable drag and drop files?

Fortunately, you can easily fix it without having to restart your computer or configure your system settings. In File Explorer, click any file or folder and hold the left button on your mouse. Then, press the Esc key. Now, try dragging and dropping again.

How do I drag and drop files in HTML?

When dropping files into drop zone you get a dataTransfer. files object, that is a FileList type of object, that contains all the files you dragged. Meanwhile, <input type="file" /> element has the property files , that is the same FileList type object. So, you can simply assign the dataTransfer.

How does file uploading work?

To upload data to a server, the client again initiates a connection to the server and then typically sends a HTTP POST request which contains the data to be uploaded. The server knows how to handle such a request and stores the data.


1 Answers

You have to use FormData (beware of IE support).

When drop happens you need to create FormData object, and append data into it, then POST that form to your url. It is asynchronous method and will not reload your page.

function drop(evt) {
  evt.stopPropogation();
  evt.preventDefault();

  var files = evt.dataTransfer.files;
  if (files.length > 0) {
    var form = new FormData();

    for(var i = 0; i < files.length; ++i) {
      var file = evt.dataTransfer.files[i];
      form.append('image_' + i, file, file.name);
    }

    var req = new XMLHttpRequest();
    req.open('POST', '/pathToPostData', true);
    req.onload = function(evt) {
      console.log(req.responseText);
    }
    req.send(form);
  }
}

Beware that I've tested it only in Chrome and Firefox, IE9 probably will not work but IE10 should, if you test it, let us know please.

like image 129
moka Avatar answered Oct 05 '22 07:10

moka