接受不在react中的文件类型中工作

发布于 2025-02-06 06:12:13 字数 627 浏览 1 评论 0原文

我正在创建一个文件上传组件,其中我必须仅允许XLSxlsx file.i am在下面写作代码。

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

但这并不限制其他文件类型。

我如何限制其他文件类型,仅允许XLSX

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

你好,陌生人 2025-02-13 06:12:15

接受属性作为其价值comma-- comma---一种或多种文件类型或唯一文件类型指定符的分离列表,描述了要允许的文件类型:

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

The accept attribute takes as its value a comma-separated list of one or more file types, or unique file type specifiers, describing which file types to allow:

<input type="file" accept=".xlsx, .xls" required  onChange={handleChange}/>
暮年慕年 2025-02-13 06:12:15

您仍然可以使用处理程序功能来验证文件扩展名。

获取文件扩展名

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

,然后检查其是否支持

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

演示

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

铃予 2025-02-13 06:12:15

您应该更新输入的accept属性如下:

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

更多有关接受: https://developer.mozilla.org/en-us/docs/web/html/attributes/accept

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文