【问题标题】:Angular - Drag-And-Drop to upload an attachmentAngular - 拖放以上传附件
【发布时间】:2019-08-13 14:42:58
【问题描述】:

我正在开发一个类似于 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();

      });
  });

}

【问题讨论】:

  • 我的回答有帮助吗?这有点复杂,但问题也很复杂......
  • @miselking 谢谢。是的,您的回答帮助我完成了这项任务,非常感谢!

标签: angular drag-and-drop


【解决方案1】:

这里有一个粗略的例子来说明如何实现这一点。首先在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

希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-12-22
    • 2013-01-27
    • 1970-01-01
    • 2012-01-21
    • 2011-09-24
    相关资源
    最近更新 更多