MIME Type 为什么物:
MIME 参考手册
svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.typeshtml
对于有文件后缀名的,能够使用 MimeMapping.GetMimeMapping 获取。web
MimeMapping.GetMimeMapping(String) Method (System.Web) | Microsoft Docsapache
若是 MimeMapping.GetMimeMapping 不认识的,会返回 application/octet-stream
这个默认值。c#
对于特定的类型的文件,能够使用与之相关的其它方式获取,如 Image ,能够这样获取:windows
public bool TryBuildFileMimeType(string filePath, out string mimeType) { if (string.IsNullOrWhiteSpace(filePath) || !System.IO.File.Exists(filePath)) { mimeType = string.Empty; return false; } try { var image = Image.FromFile(filePath); mimeType = GetMimeTypeFromImage(image); return !string.IsNullOrWhiteSpace(mimeType); } catch (Exception ex) { mimeType = string.Empty; return false; } } private string GetMimeTypeFromImage(Image image) { if (image.RawFormat.Equals(ImageFormat.Jpeg)) return "image/jpeg"; else if (image.RawFormat.Equals(ImageFormat.Bmp)) return "image/bmp"; else if (image.RawFormat.Equals(ImageFormat.Emf)) return "image/emf"; else if (image.RawFormat.Equals(ImageFormat.Exif)) return "image/exif"; else if (image.RawFormat.Equals(ImageFormat.Gif)) return "image/gif"; else if (image.RawFormat.Equals(ImageFormat.Icon)) return "image/icon"; else if (image.RawFormat.Equals(ImageFormat.Png)) return "image/png"; else if (image.RawFormat.Equals(ImageFormat.Tiff)) return "image/tiff"; else if (image.RawFormat.Equals(ImageFormat.Wmf)) return "image/wmf"; return string.Empty; }
在我这里的实际场景中,大部分文件都有后缀名,便可以用 MimeMapping 处理,对于没有后缀名的,都是图片文件,能够用后面这种方式处理。api
固然,还能够根据文件头内容,先获取文件类型,在找到对应的 MIME Type 。但这个须要本身维护一个文件头标识的表,不知道有没有现成的 NUGET 能够用,求推荐。mvc
5 Tools To Help Identify Unrecognized or Unknown File Types • Raymond.CCapp
ExifTool 这个工具很强大,能够看不少文件元数据信息,有命令行版本和GUI版本。asp.net
ExifTool by Phil Harvey
ExifToolGUIide
看到 How can I determine file type without an extension on Windows? - Super User ,
有个疑问,根据文件内容获取文件的类型/MIME type,本质上是不靠谱的?只能靠猜?只是对大部分常见文件类型,有固定格式而已?
毕竟文件内容是什么,开发者是能够任意控制的。