File API Example
HTML
<h1>File API Example</h1>
<div id="controls">
<p>Drag and drop file(s) into the blue box:</p>
<div id="filedrop"></div>
</div>
<h2>File Information</h2>
<div id="fileinfocontainer"></div>
CSS
body {
font-family: sans-serif;
padding: 10px;
}
h1 {
font-weight: bold;
}
#filedrop {
width: 250px;
height: 150px;
margin: 10px 0;
border: 1px solid #000;
background: #99CCFF;
}
#fileinfocontainer {
min-height: 25px;
width: 100%;
margin-top: 15px;
padding: 8px;
border: 1px solid #000;
}
JavaScript
//First check for support for the file API
if (!window.File || !window.FileList) {
alert("Your browser does not support the File APIs used for this example");
}
var dropbox = document.getElementById("filedrop");
//This is function is called when a drop event occurs on the dropbox area, it is passed an event object as its only parameter
function fileDropped(event) {
//Stop the the drop event from bubbling up the event chain
event.stopPropagation();
//Prevent the browsers default action occurring
event.preventDefault();
//clear the contents of the fileinfocontainer div
var fileinfocontainer = document.getElementById("fileinfocontainer");
fileinfocontainer.innerHTML = "";
//get the FileList object from the event
var droppedFiles = event.dataTransfer.files;
//get the number of files dropped in the dropbox area
var numfiles = droppedFiles.length;
//Output the number of files selected to the fileinfocontainer div
fileinfocontainer.innerHTML += "<p>You selected " + numfiles + " files<br /><br />";
//Declare i variable for 'for' loop
var i = 0;
//Loop through each of the files in the FileList
for (i = 0; i < numfiles; i++) {
//Select the file object from the FileList
var file = droppedFiles[i];
//get the file name
var filename = file.name;
//get the file type (if available)
var filetype = file.type || 'N/A';
//get the file size in Kilobytes
var filesize = Math.round(file.size / 1024);
//output the file information to the fileinfocontainer div in a .filedata container div
fileinfocontainer.innerHTML += '<div class="filedata"><h4>' + (i + 1) + '. File Name: ' + filename + '</h4><ul><li><strong>File Type: </strong>' + filetype + '</li><li><strong>File Size: </strong>' + filesize + 'kB</li></ul></div><br/>';
}
}
//This function is called when a dragover event occurs on the dropbox area, it is passed...