【问题标题】:filter file upload for only text files仅针对文本文件过滤文件上传
【发布时间】:2012-08-15 12:35:26
【问题描述】:

我使用的是 Firefox 版本 14.0.1。我需要过滤上传文件窗口以仅显示.txt 文件。

我的浏览器不仅支持文本文件(text/plain)。我可以通过指定此格式("image/*") 来限制图像文件。但我只需要在文件选择器窗口中过滤 文本文件

我的浏览器有问题吗?

【问题讨论】:

    标签: javascript html asp.net-mvc file-upload


    【解决方案1】:

    只需这样做...

    $("#form").submit(function(e) {
      e.preventDefault();
      var checkUploadFileExtension =  $('input[type=file]').val().replace(/C:\\fakepath\\/i, '').split('.').pop();
    
      if(checkUploadFileExtension === 'txt') {
        alert("Success Uploaded!");
        //Do Something
      } else {
        alert("Please upload text file only");
        //Show error
      }
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
    
    <form id="form" name="form" method="post">
      <input name="file" id="file" type="file" accept="text/*" />
      <button class="btn operations-btn btn-default" id="submit">Upload</button>
    </form>

    希望对我的帖子有所帮助。谢谢

    【讨论】:

      【解决方案2】:

      所以根据MDN reference on the input element accept=[MIME Type] 在 Gecko 中没有实现,目前你只能这样做:accept=image|audio|video

      您可以这样做的一种方法是在服务器端检查 asp.net-mvc 控制器上的类型。

      但更好的方法是在客户端上使用一些 javascript:像这样:

      <script>
      function checkExt() {
       if(document.mainForm.myfile.value.lastIndexOf(".txt")==-1) {
          alert("Please upload only .txt extention file");
          return false;
       }
      }
      </script>
      <form name="mainForm">
      <input type="file" name="myfile" onchange="checkExt();"/>
      </form>​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​
      

      在此处查看它的运行情况: http://jsfiddle.net/Egr9V/

      如果您使用 JQuery,您可以使代码更流畅或使用本文所述的验证插件: How to have jQuery restrict file types on upload?

      【讨论】:

      • 是的,我做了你已经发布的内容。但问题是我应该过滤到只显示在窗口上的文本文件。 (文本/纯文本)正在使用 chrome。它在 Firefox 中不起作用。
      • @Deva Firefox/Gecko 确实支持text/plain。我更新了我的答案。
      • Gecko 是一个 SDK。我怎样才能使它适用于 Firefox。有什么程序可以跟进吗?
      • @Deva Gecko 是 firefox 用来渲染和布局 html 的引擎。您正在寻找的功能尚未实现。您可以跟踪bug page here
      猜你喜欢
      • 2012-08-28
      • 2015-02-23
      • 1970-01-01
      • 2013-11-26
      • 1970-01-01
      • 1970-01-01
      • 2020-02-20
      • 2019-12-03
      • 2012-08-22
      相关资源
      最近更新 更多