Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

React file upload still uploads the file despite limit being set

I’m probably missing something obvious but:

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

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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
    }
  }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading