Angular File drag and drop

ngx-file-drop

Before starting File upload, I would like to mention about file handling. (for upload)

ngx-file-drop is easy implementation to support file drag and drop.

npm install ngx-file-drop --save

HTML (Angular)

This is an example in Layout(HTML)

<file-drop (onFileDrop)="dropped($event)"
                       (onFileOver)="fileOver($event)" 
                       (onFileLeave)="fileLeave($event)"
                       dropZoneClassName=""
                       contentClassName=""
                         accept="png,jpg"
                         dropZoneLabel="Drag and Drop(.png, .jpeg)">
</file-drop>

file-drop is from ngx-file-drop. This is just drag and drop space. After this, we need to implement event methods. (dropped, fileOver, fileLeave)

And in this example, we support only png, jpg.

Event

This is typescript part to use above HTML template

export class FileUploadComponent implements OnInit {
  files: UploadFile[] = [];
  targetFile;
  targetPath = null;

  public dropped(event: UploadEvent) {
    this.files = event.files;
    for (const droppedFile of event.files) {

      // Is it a file?
      if (droppedFile.fileEntry.isFile) {
        const fileEntry = droppedFile.fileEntry as FileSystemFileEntry;
        fileEntry.file((file: File) => {
          // Here you can access the real file
          if (file.type !== 'image/png' &amp;&amp; file.type !== 'image/jpeg') {
            // Error handle
            this.translate.get('ERROR.NOTSUPPORTFORMAT').subscribe((res: string) => {
              alert(res);
            });
          } else if (file.size > 1000000) {
            // Error handle
            this.translate.get('ERROR.OVERVOLUME').subscribe((res: string) => {
              alert(res);
            });
          } else {
            this.targetFile = file;
            this.targetPath = droppedFile.relativePath;
            this.imagePath = this.targetPath;
            // This part is to apply image drag and drop as preview
            // const reader = new FileReader();
            // reader.readAsDataURL(file);
           //reader.onload = () => {
           //   this.imagePath = reader.result;
           // };
          }
        });
      }
    }
  }

  public fileOver(event) {}

  public fileLeave(event) {}

}

コメント