Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML5, JavaScript: Drag and Drop File from External Window (Windows Explorer)

Can I kindly ask for a good working example of HTML5 File Drag and Drop implementation? The source code should work if drag and drop is performed from external application(Windows Explorer) to browser window. It should work on as many browsers as possible.

I would like to ask for a sample code with good explanation. I do not wish to use third party libraries, as I will need to modify the code according to my needs. The code should be based on HTML5 and JavaScript. I do not wish to use JQuery.

I spent the whole day searching for good source of material, but surprisingly, I did not find anything good. The examples I found worked for Mozilla but did not work for Chrome.

like image 636
Bunkai.Satori Avatar asked Apr 21 '12 18:04

Bunkai.Satori


1 Answers

Here is a dead-simple example. It shows a red square. If you drag an image over the red square it appends it to the body. I've confirmed it works in IE11, Chrome 38, and Firefox 32. See the Html5Rocks article for a more detailed explanation.

var dropZone = document.getElementById('dropZone');    // Optional.   Show the copy icon when dragging over.  Seems to only work for chrome.  dropZone.addEventListener('dragover', function(e) {      e.stopPropagation();      e.preventDefault();      e.dataTransfer.dropEffect = 'copy';  });    // Get file data on drop  dropZone.addEventListener('drop', function(e) {      e.stopPropagation();      e.preventDefault();      var files = e.dataTransfer.files; // Array of all files        for (var i=0, file; file=files[i]; i++) {          if (file.type.match(/image.*/)) {              var reader = new FileReader();                reader.onload = function(e2) {                  // finished reading file data.                  var img = document.createElement('img');                  img.src= e2.target.result;                  document.body.appendChild(img);              }                reader.readAsDataURL(file); // start reading the file data.          }      }  });
<div id="dropZone" style="width: 100px; height: 100px; background-color: red"></div>
like image 191
EricP Avatar answered Sep 22 '22 13:09

EricP