怎么可能只允许拖放文件?使用正常的上传按钮,它会受到限制,但无法进行拖放。
我唯一已知的解决方法是现在显示一个对话框,该对话框向用户显示所有他选择的文件,并强迫他选择其中之一。
答案 0 :(得分:1)
通常,您有一个输入类型文件和一个可拖动区域,请参见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>
定义.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;
}
并创建一个组件
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...
}
}
请注意,在功能saveFiles中,您可以检查“文件”的长度,其他可以检查的是扩展名,大小。...