Search code examples
angulartypescriptdrag-and-drop

Angular Drag and Drop, Empty files array in Event


I used my directive for file upload in another project with latest Angular, but it seems to not pass files array in dataTransfer because when I look into event(from listener), file array is empty. Please Help.

export class FileUploadDirective {
  @Input() multiple: boolean;
  @Input() accept: string[];
  @Input() maxFileSize: number;

  @Output() fileEmitter = new EventEmitter<Object>();
  constructor(
    private renderer: Renderer2,
    private elementRef: ElementRef,
    ) {
    this.multiple = false;
    this.accept = ['application/pdf'];
    this.maxFileSize = 1;
    this.renderer.setProperty(this.elementRef.nativeElement, 'draggable', true);
  }

  @HostListener('dragover', ['$event']) onDragOver(evt: DragEvent){
    evt.preventDefault();
    evt.stopPropagation();
  }

  @HostListener('drop', ['$event']) public onDrop(evt: DragEvent) {
    evt.preventDefault();
    evt.stopPropagation();

    console.log("event: ", evt);
    files = evt.dataTransfer?.files;
    
    if (files && files.length > 0) {
      let reader: FileReader = new FileReader();
      
      reader.readAsDataURL(files[0]);
      reader.onloadstart = (e) => {
        console.log('load start', this.multiple, this.accept, this.maxFileSize);
      }

      reader.onprogress = (e) => {
        console.log('load progress');
      }

Solution

  • For anyone who has this error, do not assign files = evt.dataTransfer?.files;

    it must be done by:

     console.log("event: ", evt.dataTransfer?.files.length);
        // files = evt.dataTransfer?.files;
    
        if (evt.dataTransfer!.files.length > 0) {
          let reader: FileReader = new FileReader();
    
          reader.readAsDataURL(evt.dataTransfer!.files[0]);
          reader.onloadstart = (e) => {
            console.log('load start', this.multiple, this.accept, this.maxFileSize);
          }
    

    Files lenght is correct, but compilator gets first assignment as error. Solution above for single file.