Drag And Drop File Uploader In Angular

Drag And Drop File Uploader In Angular

In this article, we will learn how to drag and drop upload file in angular using simple application example.

First, we need to create a new angular application for demonstration. use following command and create a new application.

ng new drag-drop-file-upload

In the app.component.html file, we add the following HTML code to define our drop zone.

<div *ngIf="!files.length" class="col-12 rmpm dropzone" appDragDrop (files)="filesDropped($event)">
  <div class="text-wrapper">
    <div class="centered">Drop your file here!</div>
  </div>
</div>
<!--droped image preview-->
<div *ngFor="let file of files">
  <img *ngIf="file" [src]="file.url" width="100px" height="100px">
</div>

<button type="button" (click)="upload()">Upload Image</button>

Now, we need to create directives. to do this, we must be in the folder where we want to save the directive and run the following angular-cli command.

ng generate directive drag-drop

After use above command directive has been create successfully. Now, Add HostListener next to track Drag Over, Drag Out, and then Dropping the file.

Add the following code under the drag-drop.directives.ts file.

import {
  Directive,
  HostBinding,
  HostListener,
  Output,
  EventEmitter
} from "@angular/core";
import { DomSanitizer, SafeUrl } from '@angular/platform-browser';

export interface FileHandle {
  file: File,
  url: SafeUrl
}

@Directive({
  selector: "[appDragDrop]"
})
export class DragDirective {
  @Output() files: EventEmitter<FileHandle[]> = new EventEmitter();

  @HostBinding("style.background") private background = "#eee";

  constructor(private sanitizer: DomSanitizer) { }

  @HostListener("dragover", ["$event"]) public onDragOver(evt: DragEvent) {
    evt.preventDefault();
    evt.stopPropagation();
    this.background = "#999";
  }

  @HostListener("dragleave", ["$event"]) public onDragLeave(evt: DragEvent) {
    evt.preventDefault();
    evt.stopPropagation();
    this.background = "#eee";
  }

  @HostListener('drop', ['$event']) public onDrop(evt: DragEvent) {
    evt.preventDefault();
    evt.stopPropagation();
    this.background = '#eee';
  
    let files: FileHandle[] = [];
    for (let i = 0; i < evt.dataTransfer.files.length; i++) {
      const file = evt.dataTransfer.files[i];
      const url = this.sanitizer.bypassSecurityTrustUrl(window.URL.createObjectURL(file));
      files.push({ file, url });
    }
    if (files.length > 0) {
      this.files.emit(files);
    }
  }
}

Now, add the some basic CSS for design. add the following code under the app.component.css file.

p {
  font-family: Lato;
}
.dropzone {
  min-height: 300px;
  width: 400px;
  padding:2rem;
  border:dashed 4px #979797;
  display: table;
}

.text-wrapper {
  position: absolute;
  text-align: center;
  transform: translate(50%, 50%);
}

.centered {
  font-family: sans-serif;
  font-size: 1.3em;
  font-weight: bold;
  text-align:center;
}

Now, Add the following code under the app.component.ts file to we handle the drag and drop event.

import { Component } from '@angular/core';
import { FileHandle } from './dragDrop.directive';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
 
  files: FileHandle[] = [];

  filesDropped(files: FileHandle[]): void {
    this.files = files;
  }

  upload(): void {
    //get image for upload;
  }
}

Now, run the application and see the browser screen looks like below.

Drag And Drop File Uploader In Angular

Conclusion

In this article, we learned how to drag and drop upload file in angular using simple application example.

I hope this article helps you and you will like it.👍

If you have any doubt or confusion then free to ask in comment section.

Post a Comment

Previous Post Next Post