【问题标题】:How to get type of user selected file with jQuery?如何使用 jQuery 获取用户选择的文件类型?
【发布时间】:2011-12-18 16:50:59
【问题描述】:

如何使用 jQuery 获取用户选择的文件类型(在某些 <input type="file" name="datafile"> 中),例如 alert 它?至少它的扩展,但像image 这样的某种分组类型会很有趣。有没有 jQuery 插件呢?

【问题讨论】:

标签: javascript jquery html forms file


【解决方案1】:

你为什么不使用这样的东西:

$('input:file').change(function () {
    var ext = this.value.split('.').pop();
    console.log(ext);
});

如果你想使用“多个”字段,你可以使用这样的:

$('input:file').change(function () {
    var $this = $(this);
    if ( $this.prop('multiple') ) {
        for ( var i=0; i<this.files.length; i++) { 
            var ext = this.files[i].fileName.split('.').pop();
            // this.files[i].extension = ext;  // usefull for future use
            console.log(ext);
        }
    }
    else {        
        console.log(this.value.split('.').pop());
    }
});

【讨论】:

    【解决方案2】:

    试试这个来获取你的文件扩展名。

    var fileName = "Ram.png";
    alert(fileName.substring(fileName.lastIndexOf('.') + 1)); 
    

    【讨论】:

      【解决方案3】:

      只需提供一个 id 输入并使用它

      document.getElementById(ID).files[0].type
      

      【讨论】:

      • IE 9 及更低版本不支持此功能。不过,它确实适用于 IE 10 预览版。
      • .type 将返回内容类型。示例:.xlsx 文件将返回“application/vnd.openxmlformats-officedocument.spreadsheetml.sheet”,而不是“xlsx”
      【解决方案4】:
      $('input[type=file]').change(function(e){
        var file = $(this).val();
        var ext = file.split('.').pop();
        alert(ext);
      });
      

      试试这个:)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-05-16
        • 2010-11-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-12-18
        • 1970-01-01
        相关资源
        最近更新 更多