首页 > 解决方案 > 如何在html和typescript中连续两次导入同一个文件?

问题描述

我在 html 文件中有一个输入元素,如下所示:

 <input
   type="file"
   (change)="receiveFile($event)"
   id="inputFileButton"
   hidden
 />

它正在等待用户导入文件。单击按钮时,我调用uploadFile() 方法,该方法在调用receiveFile($event) 的输入元素上发出事件。像这样:

  receiveFile($event) {
  const fileFromHtml = $event.target.files[0];
  const importedFile: FormData = new FormData();
  importedFile.append('positions', fileFromHtml);
   this.store.dispatch({
    type: '[Position] Import Positions',
    importFile: importedFile,
    positionSetId: this.positionSetId,
    accountSetId: this.accountSetId,
   });
  }

  uploadFile() {
   this.testvar = !this.testvar;
   const element: HTMLElement = document.getElementById(
     'inputFileButton',
   ) as HTMLElement;
   element.click();
  }

除了我想连续两次导入同一个文件的情况外,它工作正常。第二次它根本不调用receiveFile($event)。

标签: htmltypescript

解决方案


您的 receiveFile() 函数仅在更改事件上运行。如果输入相同的文件,没有任何改变,所以它不会运行。

为了克服这个问题,您可以尝试清除您的输入

document.getElementById("inputFileButton").value = ''

推荐阅读