Created
April 13, 2017 18:27
-
-
Save johan/3767e11d11f490eb45cf474cdc23eca9 to your computer and use it in GitHub Desktop.
HTML5 drag/drop
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<html> | |
<head> | |
<title>HTML5 drag/drop files to console.log them</title> | |
</head> | |
<body> | |
<script> | |
// this should probably be a more interesting function in your case | |
function show(...files) { | |
console.log(...files); | |
} | |
function loadFileAsText(file) { | |
return new Promise((resolve, reject) => { | |
const reader = new FileReader; | |
reader.onload = (e) => resolve(e.target.result); | |
reader.readAsText(file); | |
}); | |
} | |
function handleDrop(event) { | |
event.stopPropagation(); | |
event.preventDefault(); | |
const files = Array.from(event.dataTransfer.files); // was a FileList object | |
return Promise.all(files.map(loadFileAsText)).then(show); | |
} | |
// needed, so the native drag/drop handler won't kick in to show the dropped file | |
function handleDragOver(event) { | |
event.stopPropagation(); | |
event.preventDefault(); | |
event.dataTransfer.dropEffect = 'copy'; // Give nice visual cursor indicator | |
} | |
document.body.addEventListener('dragover', handleDragOver); | |
document.body.addEventListener('drop', handleDrop); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment