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


当前回答

**使用MediaTypeNames类——>样本:MediaTypeNames. application . pdf **

其他回答

使用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

为了让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);

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

使用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类型,请参考此文件。

为了使这篇文章更全面,对于。net核心开发人员有FileExtensionContentTypeProvider类,它涵盖了官方的MIME内容类型。

它在幕后工作——根据文件扩展名在Http响应头中设置ContentType。

如果您需要特殊的MIME类型,请参阅自定义MIME类型的示例:

public void Configure(IApplicationBuilder app)
{
    // Set up custom content types -associating file extension to MIME type
    var provider = new FileExtensionContentTypeProvider();
    // Add new mappings
    provider.Mappings[".myapp"] = "application/x-msdownload";
    provider.Mappings[".htm3"] = "text/html";
    provider.Mappings[".image"] = "image/png";
    // Replace an existing mapping
    provider.Mappings[".rtf"] = "application/x-msdownload";
    // Remove MP4 videos.
    provider.Mappings.Remove(".mp4");

    app.UseStaticFiles(new StaticFileOptions()
    {
        FileProvider = new PhysicalFileProvider(
            Path.Combine(Directory.GetCurrentDirectory(), @"wwwroot", "images")),
        RequestPath = new PathString("/MyImages"),
        ContentTypeProvider = provider
    });

    app.UseDirectoryBrowser(new DirectoryBrowserOptions()
    {
        FileProvider = new PhysicalFileProvider(
            Path.Combine(Directory.GetCurrentDirectory(), @"wwwroot", "images")),
        RequestPath = new PathString("/MyImages")
    });
}

你可以使用这个helper函数:

private string GetMimeType (string fileName)
{
    string mimeType = "application/unknown";
    string ext = System.IO.Path.GetExtension(fileName).ToLower();
    Microsoft.Win32.RegistryKey regKey = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(ext);
    if (regKey != null && regKey.GetValue("Content Type") != null)
    mimeType = regKey.GetValue("Content Type").ToString();
    return mimeType;
}