从文件扩展名获取 MIME 类型 [英] Get MIME type from filename extension

查看:39
本文介绍了从文件扩展名获取 MIME 类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从文件扩展名中获取 MIME 类型?

How can I get the MIME type from a file extension?

推荐答案

对于 ASP.NET 或其他

ASP.NET Core 中的选项略有变化,它们是(学分):

  • new FileExtensionContentTypeProvider().TryGetContentType(fileName, out contentType);(仅限 vNext)
    • 从未测试过,但看起来您可以通过公开的 Mappings 属性.

    使用 System.Web.MimeMapping.GetMimeMapping 方法,它是 .NET Framework 4.5 中 BCL 的一部分:

    Use the System.Web.MimeMapping.GetMimeMapping method, that is part of the BCL in .NET Framework 4.5:

    string mimeType = MimeMapping.GetMimeMapping(fileName);
    

    如果您需要添加自定义映射,您可能可以使用反射将映射添加到 BCL MimeMapping 类,它使用公开此方法的自定义字典,因此您应该调用以下来添加映射(从未测试过,但应该可以.

    If you need to add custom mappings you probably can use reflection to add mappings to the BCL MimeMapping class, it uses a custom dictionary that exposes this method, so you should invoke the following to add mappings (never tested tho, but should prob. work).

    无论如何,当使用反射添加 MIME 类型时,请注意,由于您正在访问私有字段,其名称可能会更改甚至被完全删除,因此您应该格外小心并添加双重检查并提供故障安全操作每一步.

    Anyway, when using reflection to add MIME types, be aware that since you're accessing a private field, its name might change or even be totally removed, so you should be extra cautious and add double checks and provide fail safe action for every step.

    MimeMapping._mappingDictionary.AddMapping(string fileExtension, string mimeType)
    

    这篇关于从文件扩展名获取 MIME 类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆