【问题标题】:How do I restrict file upload to only .xlxs and .docx files如何将文件上传限制为仅 .xlsx 和 .docx 文件
【发布时间】:2019-07-21 12:22:07
【问题描述】:

我正在开发一个只允许 .xlxs 和 .docx 文件的文件上传功能。目前,使用下面的代码,我只能将上传限制为 .xlsx。但是,我也想上传 .docx 文件,但似乎我的一段代码阻止了 .docx 文件被上传。

 if (files.length > 0) {

      if (files[0].name.lastIndexOf('.docx') === -1 || files[0].name.lastIndexOf('.xlsx') === -1) {
         $.msgbox("Please note: only excel file formats are allowed. Please download the provided upload template, see the link below.");
         this.value = '';
         return;
      }

所以上面的代码应该吐出任何不是 xlsx 或 docx 的东西,但问题是它也会吐出 docx

【问题讨论】:

  • 认为你的措辞需要改变,你要不要docx?
  • 我确实想要 docx 我已经编辑了我的问题,为错字道歉
  • 我认为你的意思是用 && 而不是 ||
  • 请记住,这绝不是安全的。因此,请确保用于文件上传的服务器端 post 处理程序也检查文件类型。一般来说,我根本不会检查客户端,我将有一个 API 有方法告诉我允许哪些文件类型,我会在用户选择文件时轮询它并根据服务器删除无效文件响应,如果他们破解 JS,api 将在无效类型上抛出错误。客户端验证是一种用户体验,根本不安全,必须在服务器端再做一次。

标签: javascript jquery file file-upload knockout.js


【解决方案1】:

您可以直接在 HTML 代码中列出受限制的文件类型:

<input type="file" accept=".xlxs,.docx">

【讨论】:

  • accept 属性对用户来说很方便,因为它过滤了文件选择弹出窗口,但它不会阻止用户选择他们想要的任何文件。您必须实际检查他们选择的内容。
【解决方案2】:

试试你的代码:

if (files[0].name.lastIndexOf('.docx') === -1 && files[0].name.lastIndexOf('.xlsx') === -1) {
     $.msgbox("Please note: only excel file formats are allowed. Please download the provided upload template, see the link below.");
     this.value = '';
     return;
}

您正在检查它是否不是 docx 并且它不是 xlsx,而不是 OR

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-12-06
    • 2021-01-27
    • 2016-12-01
    • 2016-08-22
    • 2012-05-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多