【问题标题】:Drag and drop image with image preview in angular2+以角度 2 拖放带有图像预览的图像
【发布时间】:2019-06-17 17:32:22
【问题描述】:

这里是 stackblitz 链接:- https://stackblitz.com/edit/angular6-ledera?file=app%2Fapp.component.ts

我正在尝试直接从桌面等拖放图像并放在 dropzone div 上。

1) 获取图像预览 2) 获取文件对象。

.html

<div *ngIf="!imageDrop" class="col-12 rmpm dropzone" appDrag>
    <div class="text-wrapper">
        <div class="centered">Drop your file here!</div>
    </div>
</div>
<!--droped image preview-->
<img  *ngIf="imageDrop" [src]="imageDrop" width="100px" height="100px">

dragDrop.directive.ts

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

  constructor() {}

  @HostListener("dragover", ["$event"]) public onDragOver(evt) {
    evt.preventDefault();
    evt.stopPropagation();
    this.background = "#999";
    console.log( '4444:::' + JSON.stringify(evt.target.files));
  }
  @HostListener("dragleave", ["$event"]) public onDragLeave(evt) {
    evt.preventDefault();
    evt.stopPropagation();
    this.background = "#eee";
    console.log( '222:::' + JSON.stringify(evt.target.files));
  }
  @HostListener("drop", ["$event"]) public onDrop(evt) {
    evt.preventDefault();
    evt.stopPropagation();
    let files = evt.dataTransfer.files;
    if (files.length > 0) {
      this.background = "#eee";
      console.log( '1111:::' + JSON.stringify(files));
      console.log( '33333:::' + JSON.stringify(evt.target.files));
    }
  }

【问题讨论】:

  • 您觉得我的回答有帮助吗?

标签: javascript angular html drag-and-drop image-upload


【解决方案1】:

这是一个Stackblitz demo 用于文件放置。

该指令同时处理一个或多个被删除的文件。

它以文件列表作为参数触发files 事件,每个文件都包装在一个FileHandle 接口中,其中包含file 和一个SafeUrl 用于使用window.URL.createObjectURL(file) 创建的blob。

export interface FileHandle {
  file: File,
  url: SafeUrl
}
@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);
  }
}

然后,消费组件可以使用为每个文件创建的 Url 显示图像列表。

<div *ngFor="let file of files">
  <img *ngIf="file" [src]="file.url" width="100px" height="100px">
</div>

希望对您有所帮助。

【讨论】:

    猜你喜欢
    • 2019-09-17
    • 1970-01-01
    • 2018-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多