我正在开发一个类似于 Trello 的 Angular 应用程序,我需要为客户实现拖放功能,以便能够上传附件。
问题是已经有一个从另一个组件使用的“附加”功能(没有拖放),我需要以与其他功能相同的方式实现拖放功能。(我需要采用这种“添加附件”功能进行拖放)
这里是图片说明: https://ibb.co/d5WcJfQ
我尝试观看 youtube 视频和 google-ing,但我很难按要求正确实现它。任何建议将不胜感激。
// HTML OF ATTACH COMPONENT
<span>
<a class="quiet-button js-attach">
<label class="custom-file-upload">
<input (change)="onFileChange($event)" type="file"/>
Add Attachment...
</label>
</a>
//TS FUNCTION 'onFileChange" That I need to adopt for drag-and-drop.`
onFileChange(event){
let files = event.target.files;
if (files.length > 0) {
let formData: FormData = new FormData();
for (let file of files) {
formData.append('fileName', file, file.name);
}
let file = files[0];
let attachmentData = <AttachmentInsert>{
FileName : file.name,
Path : ${this.cardHierarchy.BoardGuid}/${this.cardHierarchy.ListGuid}/${this.cardHierarchy.CardGuid}/`,
Extension : this.getExtension(file.name),
CreatedBy : this.currentUser.IdMember,
IdCard : this.idCard
};
this.cardService.addAttachment(attachmentData).subscribe(data =>{
let attachment : Attachment = data;
formData.append('filePath',attachment.Path);
this.cardService.uploadDocument(formData).subscribe(res => {
this.getAttachments();
});
});
}
最佳答案
这是一个粗略的示例,说明如何实现此目的。首先,在 html
文件中添加拖放事件:
<div (dragover)="onDragOver($event)" (drop)="onDropSuccess($event)">
<label class="custom-file-upload">
<input (change)="onChange($event)" type="file"/>
Add Attachment...
</label>
</div>
实现:
onDragOver(event) {
event.preventDefault();
}
// From drag and drop
onDropSuccess(event) {
event.preventDefault();
this.onFileChange(event.dataTransfer.files); // notice the "dataTransfer" used instead of "target"
}
// From attachment link
onChange(event) {
this.onFileChange(event.target.files); // "target" is correct here
}
private onFileChange(files: File[]) {
...
}
要添加“处理”效果,只需创建一个变量并使用它来添加/删除“处理”元素:
processing: boolean;
...
private onFileChange(files: File[]) {
this.processing = true;
this.cardService.addAttachment(attachmentData).subscribe(data => {
...
this.processing = false;
});
}
并像这样在 html
中使用它(如果设置了 processing
类,将显示 div
,并且只有当 processing
变量为 true
):
<div class="progress" [class.processing]="processing">
Processing...
</div>
<!-- in "css" -->
.progress {
display: none;
}
.progress.processing {
display: flex; // or any way to display an element
}
我添加了一个工作示例 here .
希望这对您有所帮助。
关于Angular - 拖放上传附件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57480159/