File Drag and Drop
by vapocalypse
HTML
<textarea readonly="readonly" id="result"></textarea>
<div id="dragBox">
<div id="dropMsg">
Drop file here
</div>
</div>
<div id="topDiv"></div>
CSS
#result {
z-index: 0;
position: absolute;
margin: 0px;
width: 100%;
height: 100%;
}
#dragBox {
z-index: 999;
position: absolute;
background: white;
left: 50%;
top: 50%;
margin-left: -125px;
margin-top: -25px;
height: 50px;
width: 250px;
border: 3px solid black;
display: none;
}
#dropMsg {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
margin: auto;
height:18px;
text-align: center;
text-font-size: 18px;
}
#topDiv {
position: fixed;
width: 100%;
height: 100%;
z-index: 1000;
display: none;
}
JavaScript
function handleFileDrop(files) {
for (var i = 0; i < files.length; i++) {
var fileName = files[i].name;
var fileType = files[i].type;
var fileSize = files[i].size;
var r = new FileReader();
r.onload = function(e) {
var contents = e.target.result;
var extensionPat = /.*\.(js|txt|html|java|c|cpp|sql)$/i;
var mimePat = /^text.*/i;
if (!extensionPat.test(fileName) && !mimePat.test(fileType)) {
contents = btoa(contents);
fileSize = contents.length;
}
$('#result').val("Got the file.\n"
+ "\tname: " + fileName + "\n"
+ "\ttype: " + fileType + "\n"
+ "\tsize: " + fileSize + " bytes\n"
+ "\tcontents:\n\n" + contents);
}
r.readAsBinaryString(files[i]);
}
}
$(document).ready(function() {
$('#result').bind("dragenter", function(e) {
$('#dragBox, #topDiv').show();
});
$('#topDiv').bind("dragleave dragout", function(e) {
$('#dragBox, #topDiv').hide();
});
$('#topDiv').bind("dragover", function(e) {
e.preventDefault();
return false;
});
$('#topDiv').bind("drop", function(e) {
e.preventDefault();
e.stopPropagation();
e.originalEvent.preventDefault();
e.originalEvent.stopPropagation();
$('#dragBox, #topDiv').hide();
var dt = e.originalEvent.dataTransfer;
var files = dt.files;
handleFileDrop(files);
return false;
});
});