Angular file drag and drop not working in Chrome

Viewed 44

I have created a file upload component in Angular that uses the @HostListener('drop', ['$event']). In Firefox I receive the files I drop in event.dataTransfer.files, but for some reason Chrome will always return the same event object with an empty list instead of the File objects for the files I dropped.

Here's a snippet of the file drop listener

@HostListener('drop', ['$event'])
  public onDrop(evt: any) {
    evt.preventDefault();
    evt.stopPropagation();
    document.getElementById('dropzone')?.classList.remove('hovering');
    console.log(evt); // Returns an event object without any files in it.

    for (let i = 0; i < evt.dataTransfer.files.length; i++) {
      // ... do stuff
    }

    // Add files to input field programmatically
    const fileInput = document.getElementById('form-file-input') as any;
    if (fileInput && fileInput.files) {
      fileInput.files = dataTransfer.files;
    }

    // Fire change event
    fileInput.dispatchEvent(new Event('change'));
  }

And my relevant HTML

<div class="dropzone" id="dropzone">
  <label for="form-file-input">Drop files here</label>
</div>

<input
  type="file"
  id="form-file-input"
  name="file"
  class="form-control file-upload"
  [formControl]="formControl"
  [formlyAttributes]="field"
  accept="image/*"
  style="display: none"
/>

I am also using Formly to create the forms but I'm pretty sure the bug isn't in there since all relevant code gets executed. I just don't receive the file object from the client.

0 Answers
Related