如何将文件上传限制为仅.xlxs和.docx文件

时间:2019-02-27 17:28:50

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

我正在研究文件上传功能,该功能仅应允许.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

2 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分:1)

尝试这样的代码:

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