这里是 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));
}
}
最佳答案
Here is a Stackblitz demo for the file drop.
该指令处理一次删除的一个或多个文件。
它会触发一个以文件列表作为参数的 files
事件,每个文件都包装在包含 file 的 FileHandle
接口(interface)中。和一个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>
希望有帮助。
关于javascript - 拖放图像并以 Angular 2 进行图像预览,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54338889/