Skip to content

Instantly share code, notes, and snippets.

@johan
Created April 13, 2017 18:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save johan/3767e11d11f490eb45cf474cdc23eca9 to your computer and use it in GitHub Desktop.
Save johan/3767e11d11f490eb45cf474cdc23eca9 to your computer and use it in GitHub Desktop.
HTML5 drag/drop
<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