Skip to content

Instantly share code, notes, and snippets.

@johan johan/index.html
Created Apr 13, 2017

Embed
What would you like to do?
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
You can’t perform that action at this time.