Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

187
Visualizações
How to validate files users are sending before uploading it to a server? - Javascript

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>
about 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

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>
about 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda