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


当前回答

我已经编写了一个程序来获取和转换Apache mime。类型文件到c#字典<字符串,字符串>的关键文件扩展名。这里的。

实际的输出是这个文件(但是您可能希望获取它并再次运行它,以防Apache文件在我上次运行之后已经更新)。

public static Dictionary<string, string> MimeTypes = new Dictionary<string, string>
{
  { "123", "application/vnd.lotus-1-2-3" },
  { "3dml", "text/vnd.in3d.3dml" },
  { "3g2", "video/3gpp2" },
  { "3gp", "video/3gpp" },
  { "7z", "application/x-7z-compressed" },
  { "aab", "application/x-authorware-bin" },
  { "aac", "audio/x-aac" },
  { "aam", "application/x-authorware-map" },
  { "aas", "application/x-authorware-seg" },
  { "abw", "application/x-abiword" },
  ...

其他回答

.NET Core获取MimeType的方法:

添加依赖关系

Microsoft.AspNetCore.StaticFiles

private string GetMimeType(string fileName)
{
    var provider = new FileExtensionContentTypeProvider();
    if (!provider.TryGetContentType(fileName, out var contentType))
    {
        contentType = "application/octet-stream";
    }
    return contentType;            
}

Bryan Denny上面的帖子不适合我,因为不是所有的扩展在注册表中都有一个“内容类型”子键。我不得不调整代码如下:

private string GetMimeType(string sFileName)
{
  // Get file extension and if it is empty, return unknown
  string sExt = Path.GetExtension(sFileName);
  if (string.IsNullOrEmpty(sExt)) return "Unknown file type";

  // Default type is "EXT File"
  string mimeType = string.Format("{0} File", sExt.ToUpper().Replace(".", ""));

  // Open the registry key for the extension under HKEY_CLASSES_ROOT and return default if it doesn't exist
  Microsoft.Win32.RegistryKey regKey = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(sExt);
  if (regKey == null) return mimeType;

  // Get the "(Default)" value and re-open the key for that value
  string sSubType = regKey.GetValue("").ToString();
  regKey = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(sSubType);

  // If it exists, get the "(Default)" value of the new key
  if (regKey?.GetValue("") != null) mimeType = regKey.GetValue("").ToString();

  // Return the value
  return mimeType;
}

现在它可以为我所有注册的文件类型和未注册的或通用的文件类型(如JPG等)。

为了让Shimmy的回答更清楚:

var mimeType = MimeMapping.GetMimeMapping(fileName);

System.Web.dll v4.5开发

// Summary:
//     Returns the MIME mapping for the specified file name.
//
// Parameters:
//   fileName:
//     The file name that is used to determine the MIME type.
public static string GetMimeMapping(string fileName);

使用MimeTypeMap包,它提供了文件扩展名到mime类型以及mime类型到文件扩展名的巨大双向映射

使用mimetype;

获取扩展的mime类型

Console.WriteLine("txt -> " + MimeTypeMap.GetMimeType("txt"));  // "text/plain"

获取mime类型的扩展名

Console.WriteLine("audio/wav -> " + MimeTypeMap.GetExtension("audio/wav")); // ".wav"

GitHub网址:https://github.com/samuelneff/MimeTypeMap

您不应该信任来自客户端的文件扩展名。总是检查文件的神奇数字。

使用filetpe讯问器与ASP。NET核心:

public static class FileTypeChecker
{
    private static List<string> validVideoMimeTypes = new List<string> { "video/mp4", "video/quicktime" };
    private static List<string> validImageMimeTypes = new List<string> { "image/png", "image/jpeg" };

    public static bool IsValidVideo(IFormFile file)
    {
        return validVideoMimeTypes.Contains(GetFileMimeType(file));
    }

    public static bool IsValidImage(IFormFile file)
    {
        return validImageMimeTypes.Contains(GetFileMimeType(file));
    }

    private static string GetFileMimeType(IFormFile file)
    {
        // You should have checked for null and file length before reaching here

        IFileTypeInterrogator interrogator = new FileTypeInterrogator.FileTypeInterrogator();

        byte[] fileBytes;
        using (var stream = new MemoryStream())
        {
            file.CopyTo(stream);
            fileBytes = stream.ToArray();
        }

        FileTypeInfo fileTypeInfo = interrogator.DetectType(fileBytes);
        return fileTypeInfo.MimeType.ToLower();
    }
}

在你的控制器或服务内部:

public IActionResult UploadVideo([FromForm] UploadVideoVM model)
{
    if (model.File.Length < minimumLength || model.File.Length > maximumLength)
    {
        // BadRequest => Size
    }
    else if (!FileTypeChecker.IsValidVideo(model.File))
    {
        // BadRequest => Type
    }
    else
    {
        // All good
    }

    return Ok();
}

要获得文件扩展名的MIME类型,请参考此文件。