Prevent browser from loading a drag-and-dropped file

前端 未结 10 2036
逝去的感伤
逝去的感伤 2020-11-28 02:12

I\'m adding an html5 drag and drop uploader to my page.

When a file is dropped into the upload area, everything works great.

However, if I accidentally drop

10条回答
  •  没有蜡笔的小新
    2020-11-28 02:27

    Note: Although the OP did not ask for an Angular solution, I came here looking for that. So this is to share what I found to be a viable solution, if you use Angular.

    In my experience this problem first arises when you add file drop functionality to a page. Therefore my opinion is that the component that adds this, should also be responsible for preventing drop outside of the drop zone.

    In my solution the drop zone is an input with a class, but any unambiguous selector works.

    import { Component, HostListener } from '@angular/core';
    //...
    
    @Component({
      template: `
        
    ` }) export class MyComponentWithDropTarget { //... @HostListener('document:dragover', ['$event']) @HostListener('drop', ['$event']) onDragDropFileVerifyZone(event) { if (event.target.matches('input.dropzone')) { // In drop zone. I don't want listeners later in event-chain to meddle in here event.stopPropagation(); } else { // Outside of drop zone! Prevent default action, and do not show copy/move icon event.preventDefault(); event.dataTransfer.effectAllowed = 'none'; event.dataTransfer.dropEffect = 'none'; } } }

    The listeners are added/removed automatically when component is created/destroyed, and other components using the same strategy on the same page do not interfere with each other due to the stopPropagation().

提交回复
热议问题