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

Time:04-26

Had minimal luck.

In the below code snippet, I tried to first prevent event propagation so it wouldn't upload just yet.

I had the following assumptions.

  1. Default browser action will happen before my event listener gets hit.
  2. I can dispatch the event again afterward.
<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>

CodePudding user response:

This seems to have worked. The problem was I couldn't just dispatch the same event I stopped propagation from, as well as changing from 'click' handler to 'change' handler so i can view files after the file dialog have completed.

<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>
  • Related