File API - Drag and Drop
by cmar4
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;
}
JavaScript
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 + "</li>";
}
var output = document.getElementById("result");
output.innerHTML = "<ul>" + filesInfo + "</ul>";
}
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");
}
}