如何在将文件上传到服务器之前验证用户发送的文件? - Javascript

How to validate files users are sending before uploading it to a server? - Javascript

运气极差。

在下面的代码片段中,我尝试首先阻止事件传播,因此它不会立即上传。

我有以下假设。

  1. 默认浏览器操作将在我的事件侦听器被命中之前发生。
  2. 之后我可以再次发送事件。
<html>
  <input id="file-input" type="file">
</html>

...

<script>
  let ignoreEventForSecondTime = false
  document.getElementById("file-input").addEventListener("click", (event) => {
    if (!ignoreEventForSecondTime) {
      event.stopImmediatePropagation() // Don't actually upload yet
      const input = event.target
      validate(input.files) // I only want this to run after users have picked the files
      ignoreEventTheSecondTime = true // Don't run this block after I refire the event
      input.dispatchEvent(event) // The intention is to let whatever event listener handle uploading the files afterwards.
    } else {
      ignoreEventTheSecondTime = false
    }
    
  }, { capturing: true })
</script>

这似乎奏效了。问题是我不能只发送我停止传播的同一个事件,也不能从 'click' 处理程序更改为 'change' 处理程序,这样我就可以在文件对话框完成后查看文件。

<html>
  <input id="file-input" type="file">
</html>

...

<script>
  let ignoreEventForSecondTime = false
  document.getElementById("file-input").addEventListener("change", (event) => { // LINE CHANGED
    if (!ignoreEventForSecondTime) {
      event.stopImmediatePropagation() // Don't actually upload yet
      const input = event.target
      validate(input.files)
      ignoreEventTheSecondTime = true // Don't run this block after I refire the event
      input.dispatchEvent(new Event('change', event)) // LINE CHANGED
    } else {
      ignoreEventTheSecondTime = false
    }
    
  }, { capturing: true })
</script>