Drag And Drop Accepts Dropped Files
preventDefault dragenter, dragover, and drop so the browser does not open the file, then read event.dataTransfer.files and accept images by MIME type.
Code
// 浏览器默认把 drop 当作“打开文件”:三类事件都必须 preventDefault
const dropZone = document.querySelector('#drop-zone');
for (const type of ['dragenter', 'dragover', 'drop']) {
dropZone?.addEventListener(type, (event) => event.preventDefault());
}
dropZone?.addEventListener('drop', (event) => {
const files = [...event.dataTransfer.files];
const images = files.filter((file) => file.type.startsWith('image/'));
const rejected = files.filter((file) => !file.type.startsWith('image/'));
for (const file of images) {
console.log('accepted:', file.name, '(' + file.type + ',', file.size, 'bytes)');
}
for (const file of rejected) {
console.log('rejected:', file.name, '- images only');
}
});How it works
Iteration is nested: for (const type of ['dragenter', 'dragover', 'drop']) frames the pass, for (const file of images) does the per-item step.
Everything operates on top-level bindings: dropZone.
What to watch for
documentexist only in browsers — a Node runtime has no shims for them out of the box.
Using it
Running the file prints labeled results such as accepted:, rejected: — each operation’s effect is visible in the output.
Key statements
dropZone?.addEventListener(type, (event) => event.preventDefault());
const rejected = files.filter((file) => !file.type.startsWith('image/'));
const images = files.filter((file) => file.type.startsWith('image/'));
FAQ
- Does Drag And Drop Accepts Dropped Files run in plain Node.js?
- No — it touches `document`, which exist only in the browser. Run it in a page (or the DevTools console) instead of a bare Node process.
Report a problem with this exampleOpens a pre-filled issue on GitHub.