Home > database >  File get uploaded despite limit being set, input not getting emptied
File get uploaded despite limit being set, input not getting emptied

Time:08-17

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
    }
  }

CodePudding user response:

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