CptDayDreamer
CptDayDreamer

Reputation: 1794

Angular File Drag and Drop allow only single file

How is it possible to allow only to drag and drop only file? With the normal upload button it's restricted but drag and drop does not work.

My only known workaround would be a dialog now that shows the user all his selected files and forces him to choose one of them.

Upvotes: 0

Views: 9953

Answers (1)

Eliseo
Eliseo

Reputation: 58099

in general, you has an input type file and a dragable zone see a stackblitz example

<div draggable="true" ngClass="{{dragAreaClass}}">
    <div class="row">
        <div class="col-md-12 text-center">
            Drag files here
            <a href="javascript:void(0)" (click)="file.click()">
                or click to open
            </a>
            <input type="file"
                   #file
                   [multiple]="false"
                   (change)="onFileChange($event)"
                   style="display:none" />
        </div>
        </div>
    </div>
    <div class="error" *ngIf="error">
        Only one file at time allow
    </div>

Where you defined the .css

.error {
    color: #f00;
}

.dragarea {
    font-size: 1.5rem;
    border: 3px solid #bbb;
    padding: 1.5rem;
    background-color: #fff;
    color: #bbb;
}

.droparea {
  font-size: 1.5rem;
  border: 3px dashed #bbb;
  padding: 1.5rem;
  background-color: #eff;
  color: #aaa;
}

And create a component

  error: string;
  dragAreaClass: string;
  onFileChange(event: any) {
    let files: FileList = event.target.files;
    this.saveFiles(files);
  }
  ngOnInit() {
    this.dragAreaClass = "dragarea";
  }
  @HostListener("dragover", ["$event"]) onDragOver(event: any) {
    this.dragAreaClass = "droparea";
    event.preventDefault();
  }
  @HostListener("dragenter", ["$event"]) onDragEnter(event: any) {
    this.dragAreaClass = "droparea";
    event.preventDefault();
  }
  @HostListener("dragend", ["$event"]) onDragEnd(event: any) {
    this.dragAreaClass = "dragarea";
    event.preventDefault();
  }
  @HostListener("dragleave", ["$event"]) onDragLeave(event: any) {
    this.dragAreaClass = "dragarea";
    event.preventDefault();
  }
  @HostListener("drop", ["$event"]) onDrop(event: any) {
    this.dragAreaClass = "dragarea";
    event.preventDefault();
    event.stopPropagation();
    if (event.dataTransfer.files) {
      let files: FileList = event.dataTransfer.files;
      this.saveFiles(files);
    }
  }

  saveFiles(files: FileList) {
    if (files.length > 1) this.error = "Only one file at time allow";
    else {
      this.error = "";
      console.log(files[0].size,files[0].name,files[0].type);

      ..use a sevice to upload file...
    }
  }

See that in the function saveFiles you can check the length of "files", other things that you can check is the extension, the size....

Upvotes: 4

Related Questions