Skip to content

Instantly share code, notes, and snippets.

@sleepygarden
Created February 8, 2016 19:02
Show Gist options
  • Save sleepygarden/8b35dca6a6698350b046 to your computer and use it in GitHub Desktop.
Save sleepygarden/8b35dca6a6698350b046 to your computer and use it in GitHub Desktop.
Handle click to upload and drag to upload
function init(){
// default behavior is always show copy icon, open file in new window. override that!
window.addEventListener('dragover', function(e){
e.stopPropagation();
e.preventDefault();
e.dataTransfer.dropEffect = 'none';
});
window.addEventListener('drop', function(e){
e.stopPropagation();
e.preventDefault();
});
var dropZone = document.getElementById('dropzone');
dropZone.addEventListener('dragover', function(e) {
e.stopPropagation();
e.preventDefault();
e.dataTransfer.dropEffect = 'copy';
});
dropZone.addEventListener('drop', function(e) {
e.stopPropagation();
e.preventDefault();
handleUploads(e.dataTransfer.items);
});
var clickToUpload = document.getElementById('uploadBtn');
var uploadInput = document.getElementById('uploadInput');
clickToUpload.onclick = function() {
uploadInput.click();
};
uploadInput.addEventListener('change', function(e) {
handleUploads(e.target.files); // the name "files" may be contingent on <input name="files[]">
}, false);
}
function handleUploads(items){
for (var idx=0, len=items.length; idx < len; idx++){
var file = items[idx];
if (file.constructor === DataTransferItem){
file = file.webkitGetAsEntry();
if (file.isFile){
handleDataTransferItem(file);
}
else if (file.isDirectory){
expandDirectory(file);
}
}
else if (file.constructor === File){
readFile(file);
}
}
}
function expandDirectory(directory){
var dirReader = directory.createReader();
dirReader.readEntries(function(results){
results.forEach(function(subItem){
if (subItem.isFile){
handleDataTransferItem(subItem);
}
else if (subItem.isDirectory){
expandDirectory(subItem);
}
});
});
}
function handleDataTransferItem(entry){
// skip dot files which are in nested folders, zips, etc
if (entry.name.startsWith('.')){
return;
}
function onFileWrite(file){
if (file.fullPath === undefined){
file.fullPath = entry.fullPath;
}
readFile(file);
}
function onFileWriteError(error){
console.error('could not write out file entry!', error);
}
entry.file( onFileWrite, onFileWriteError);
}
function readFile(file){
if (file.name.startsWith('.')){
return;
}
if (file.fullPath === undefined){
file.fullPath = file.name;
}
var fileReader = new FileReader();
fileReader.onload = function(e) {
parseFile(file, e.target.result);
};
fileReader.onerror = function(e){
console.error('can not read file contents',e);
};
fileReader.readAsText(file);
}
function parseFile(file, fileContents){
// deal with file
}
init();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment