使用Html5文件api确定未知内容类型

Jes*_*sse 12 javascript html5 file-upload

我正在处理一个小文件上传脚本(学习经验),我注意到在选择微软办公室相关文件(.doc或者.docx例如)时,文件对象没有指定类型:

文件列表

对于.doc文件,我原本期望的类型是"application/msword"和.docx一样的思路"application/vnd.openxmlformats-officedocument.wordprocessingml.document".

在无法确定类型的情况下,查看文件扩展名并将其与"预期"内容/ mime类型匹配的正确操作过程是什么?

示例脚本:

<div id="fileUpload">
    <input type="file" id="fileElem" style="display:none;" onchange="handleFiles(this.files)"/>
    <a href="#" id="fileSelect">Select some files</a>
</div>

<script type="text/javascript">
    var fileSelect = document.getElementById("fileSelect"),
        fileElem = document.getElementById("fileElem");

    fileSelect.addEventListener("click", function (e) {

        if (fileElem) {
            fileElem.click();
        }

        e.preventDefault();
    }, false);

    function handleFiles(files) {
        console.log(files);
    }

</script>
Run Code Online (Sandbox Code Playgroud)

小智 15

根据W3 ​​File Api Draft的类型归属:

小写的ASCII编码字符串,表示Blob的媒体类型,表示为RFC2046 MIME类型[RFC2046].在获取时,符合要求的用户代理应该返回Blob的MIME类型(如果已知).如果符合要求的用户代理无法确定Blob的媒体类型,则它们必须返回空字符串.如果字符串与RFC 2616的3.7"媒体类型"部分中定义的媒体类型令牌匹配,则该字符串是有效的MIME类型

所以基本上,如果它不是HTTP/1.1的有效或媒体类型,它将是空的.无论如何.

是的,你应该这样做:

if(type === "") {
  //Get extension and match to a MIME-types list. (http://www.htmlquick.com/es/reference/mime-types.html)
}
Run Code Online (Sandbox Code Playgroud)


Cha*_*had 11

同意接受的答案,但作为对某人(像我一样)的一个FYI,因为为某些人而不是特定文件类型的其他人发生了这种情况,请注意在Windows中,如果没有适当地设置mime在用户注册表中,您将获得空字符串.这是一个有趣的几个小时:)