File API - Drag and Drop

by Christopher O

HTML

<!DOCTYPE html>
<html>

  <head>
    <title>File API</title>
  </head>

  <body>
    <header>
      <h1>File API</h1>
    </header>
    <article>
      <div id="drop_area" class="area">Drop your files here!</div>
      <output id="result" />
    </article>
  </body>

</html>

CSS

body {
  font-family: 'Segoe UI';
  font-size: 12pt;
}

header h1 {
  font-size: 12pt;
  color: #fff;
  background-color: #1BA1E2;
  padding: 20px;
}

article {
  width: 80%;
  margin: auto;
  margin-top: 10px;
}

.area {
  border: 5px dotted #ccc;
  padding: 50px;
  text-align: center;
}

.drag {
  border: 5px dotted green;
  background-color: yellow;
}

#result ul {
  list-style: none;
  margin-top: 20px;
}

#result ul li {
  border-bottom: 1px solid #ccc;
  margin-bottom: 10px;
}

img.preview {
  width: 200px;
  background-color: white;
  border: 1px solid #DDD;
  padding: 5px;
}

JavaScript

console.clear();

function dragHandler(event) {
  event.stopPropagation();
  event.preventDefault();

  var drop_area = document.getElementById("drop_area");
  drop_area.className = "area drag";
}

function filesDroped(event) {
  event.stopPropagation();
  event.preventDefault();

  drop_area.className = "area";

  var files = event.dataTransfer.files; //It returns a FileList object
  var filesInfo = "";

  for (var i = 0; i < files.length; i++) {
    var file = files[i];

    filesInfo += "<li>Name: " + file.name + "</br>" + " Size: " + file.size + " bytes</br>" + " Type: " + file.type + "</br>" + " Modified Date: " + file.lastModifiedDate;

    var reader = new FileReader();

    reader.addEventListener("load", function() {
      var imageData = reader.result;
      
      if(imageData){
        filesInfo += '<br><img class="preview" src="'+imageData+'">';
      }else{
        filesInfo += '<br>*no imageData*';
      }
      
    }, false);

    if (file) {
      reader.readAsDataURL(file);
    }else{
      filesInfo += '<br>*no file*';
    }





    filesInfo += "</li>";

    //filesInfo += "<li>" + JSON.stringify(file) + "</li>";

  }

  var output = document.getElementById("result");

  output.innerHTML = "<ul>" + filesInfo + "</ul>";

  output.innerHTML += JSON.stringify(files);
}

window.onload = function() {

  //Check File API support
  if (window.File && window.FileList) {
    var drop_area = document.getElementById("drop_area");

    drop_area.addEventListener("dragover", dragHandler);
    drop_area.addEventListener("drop", filesDroped);

  } else {
    console.log("Your browser does not support File API");
  }
}