简体   繁体   中英

how to restrict file upload or drag and drop for pdf files only using angular13 without any 3rd party tools or plugins

i am using Angular13 and here i need to restrict file upload for pdf files only, for browse i was able to handle by using accept=".pdf" but not able to restrict for drag and drop files, i have used directive for that.

HTML:

Directive:

@Directive({
    selector: '[appDragDrop]'
  })
  export class DragDirective {
    @Output() onFileDropped = new EventEmitter<any>();

    //Dragover listener
    @HostListener('dragover', ['$event']) onDragOver(evt:any) {
      evt.preventDefault();
      evt.stopPropagation();
    }
    //Dragleave listener
    @HostListener('dragleave', ['$event']) public onDragLeave(evt:any) {
      evt.preventDefault();
      evt.stopPropagation();
    }
    //Drop listener
    @HostListener('drop', ['$event']) public ondrop(evt:any) {
      evt.preventDefault();
      evt.stopPropagation();
      let files = evt.dataTransfer.files;
      if (files.length > 0) {
        this.onFileDropped.emit(files)
      }
  
    }

You're drop events will contain event.dataTransfer arguments. That's where you handle mime types.

Each file in event.dataTransfer.files you can access their type .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM