Skip to content
Advertisement

File gets uploaded despite limit being set, input not getting emptied

I’m probably missing something obvious but once I confirm the ok in the window.alert the file name still appears next to Choose File? So it’s being uploaded to the input still. How do I prevent this?

<input id="uploadFile" type="file" onChange={chooseFile} />
  const chooseFile = (e) => {
    e.preventDefault()
    const file = e.target.files[0]
    if (file.size > 2e6) {
      window.alert("Please upload a file smaller than 2 MB")
      e.target.file = ""
      return false
    }
  }

Advertisement

Answer

Empty the value property of the input. For that change e.target.file = "" to e.target.value = "". Here is your hole code:

const chooseFile = (e) => {
    e.preventDefault()
    const file = e.target.files[0]
    if (file.size > 2e6) {
      window.alert("Please upload a file smaller than 2 MB")
      e.target.value = ""
      return false
    }
  }
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement