javascript MIME 类型的文件扩展名

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6246810/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 20:02:53  来源:igfitidea点击:

File name extension to MIME type

javascriptjquerydojomime-types

提问by khan

Using only JavaScript and framework like dojo/jQuery...

只使用 JavaScript 和像 dojo/jQuery 这样的框架......

Is there a way to find the Content-Type for a particular file name extension?

有没有办法找到特定文件扩展名的内容类型?

Say if I type in the string "something.pdf", I want to show an alert that says "application/pdf"

假设我输入字符串“something.pdf”,我想显示一个提示“application/pdf”

or "something.html" show "text/html"?

或“something.html”显示“text/html”?

回答by alex

I think you will need to maintain the mappings yourself (you couldXHR a physical file and get it, but I doubt you want to do that)...

我认为您需要自己维护映射(您可以XHR 物理文件并获取它,但我怀疑您是否愿意这样做)...

(function() {

    var extToMimes = {
       'img': 'image/jpeg',
       'png': 'image/png',
       ...
    }

    window.getMimeByExt = function(ext) {
        if (extToMimes.hasOwnProperty(ext)) {
           return extToMimes[ext];
        }
        return false;
    }

})();

jsFiddle.

js小提琴

This will return falseif it doesn't exist in your mapping. If you like, you could just return the extToMimes[ext], which will give undefinedif it doesn't exist. It also won't accidentally get things up the prototype chain.

false如果它在您的映射中不存在,它将返回。如果你愿意,你可以只返回extToMimes[ext]undefined如果它不存在,它将给出。它也不会意外地使原型链上升

There is also the option of accessing it if it is a file input.

如果它是一个文件,也可以选择访问它input

var mime = $('input[type="file"]').prop('files')[0].file;

Keep in mind the extension to mime type makes no guarantees about the actual file itself; you'd need to parse it server side to determine what kind of file it really is.

请记住,mime 类型的扩展名不能保证实际文件本身;您需要在服务器端解析它以确定它到底是什么类型的文件。

回答by Ahmed elshiekh

you can use node-mime

你可以使用node-mime

<script src="https://wzrd.in/standalone/mime@latest"></script>
<script>
    mime.getType("something.pdf"); // etc.
<script>