Home > Net >  accept is not working in file type in react
accept is not working in file type in react

Time:06-10

I am creating a file upload component in which I have to allow only xls or xlsx file.I am writing below code.

      <div>
        <form onSubmit={handleSubmit}>
          <input type="file" accept="xlsx/*" required  onChange={handleChange}/>
          <button type="submit" className='submitbutton'>Import Bulk User</button>
        </form>
      </div>

but it is not restricting other file types.

enter image description here

how can I restrict other file types and allow only xlsx

CodePudding user response:

You could still use your handler function to validate the file extension.

Get the file extension by

 event.target.files[0].name.split(".")[1];

and then check if its supported or not

if (allowedExtension.includes(fileExtension)) {
    console.info("correct file uploaded!");
    // set file to state
    setUploadedFile(file);
} else {
    console.error("incorrect file extension");
    // show error
}

DEMO

CodePudding user response:

Maybe this is obvious, but why not just use:

<input type="file" accept=".xlsx, .xls" required  onChange={handleChange}/>

?

CodePudding user response:

You should update your input's accept attribute as below:

<input type="file" accept=".xls,.xlsx" required  onChange={handleChange}/>

More about accept: https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/accept

  • Related