【问题标题】:How can I set the type of upload of a file in an html as excel only?如何将html中文件的上传类型设置为仅excel?
【发布时间】:2016-12-05 07:41:26
【问题描述】:

Image here shows how one can manipulate the browser to choose a different file我已经就类似问题经历了大量的问题和答案,但到目前为止没有找到任何帮助。目前的方法有很多,其中比较突出的是:

<input type="file" id="fileSelect"
       accept=".csv,
               application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,
               application/vnd.ms-excel">

但是,这并不能解决我的问题。用户仍然可以在浏览器中将文件类型更改为 All Files 并选择不同的文件。我想知道是否有任何方法可以限制用户只选择 excel 文件。

【问题讨论】:

标签: javascript html excel file input


【解决方案1】:

您可以使用change 事件来检查所选文件.type 是否与accept 属性类型之一匹配

var input = document.getElementById("fileSelect");
input.addEventListener("change", function(e) {
  if (!new RegExp(this.accept.replace(/,/g, "|")).test(this.files[0].type)) {
     this.value = "";
     this.labels[0].innerHTML = "Invalid file type selected. "
                                + "Please select one of <code>" 
                                + this.accept 
                                + "</code> file types";
  } else {
    console.log("valid file type", this.files[0].type);
    this.labels[0].innerHTML = "";
    // do stuff
  }
})
[for="fileSelect"] {
  color:red;
}
<input type="file" id="fileSelect" accept=".csv,
               application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,
               application/vnd.ms-excel"><br>
<label for="fileSelect"></label>

【讨论】:

  • 这个答案真的很有帮助,虽然我现在明白我所希望的无法实现。这是我能做的最好的。谢谢! :)
猜你喜欢
  • 2020-07-31
  • 1970-01-01
  • 1970-01-01
  • 2015-12-13
  • 1970-01-01
  • 2011-10-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多