<input type =“ file” />事件

时间:2018-08-21 08:36:24

标签: javascript html reactjs

我需要编写一个接受CSV文件的文件输入,对其进行验证,如果文件中有错误,则不会上传。这是React Component的代码:

<CustomInput
 type="file"
 id="fileBrowser"
 name="file"
 label={filename || 'Choose CSV'}
 onChange={this.loadFile}
 accept="text/csv"
 invalid={!file.isValid}
/>

所以我有问题:onChange事件仅在输入文件更改时才处理。想象一下,我输入了无效的CSV文件,得到错误,在此文件中找到它,更正并尝试再次加载该文件,但是onChange事件无法处理,因为输入由于其名称而认为我具有相同的文件。我发现的唯一解决方法是加载另一个文件,然后再次加载旧文件或更改旧文件的名称。

如果还有其他解决方案?

1 个答案:

答案 0 :(得分:0)

当发现文件无效时,将Input的值设置为null

function foo() {
  var fileInput = document.querySelector(`input[name="myFile"]`);
  // your logic tho file that the file was invalid
  // if invalid
  fileInput.value = null;
  console.log("onchange called");
  
}
<input type="file" name="myFile" onchange="foo()">