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


当前回答

. net框架提供了获取mime类型的内置方法。不需要编写自定义代码。

string mimeType = System.Web.MimeMapping.GetMimeMapping(fileName);

其他回答

为了使这篇文章更全面,对于。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")
    });
}

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

我对这些mimetypes的理解,使用apache列表,下面的脚本将为您提供一个包含所有mimetypes的字典。

var mimeTypeListUrl = "http://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types";
var webClient = new WebClient();
var rawData = webClient.DownloadString(mimeTypeListUrl).Split(new[] { Environment.NewLine, "\n" }, StringSplitOptions.RemoveEmptyEntries);

var extensionToMimeType = new Dictionary<string, string>();
var mimeTypeToExtension = new Dictionary<string, string[]>();

foreach (var row in rawData)
{
    if (row.StartsWith("#")) continue;

    var rowData = row.Split(new[] { "\t" }, StringSplitOptions.RemoveEmptyEntries);
    if (rowData.Length != 2) continue;

    var extensions = rowData[1].Split(new[] { " " }, StringSplitOptions.RemoveEmptyEntries);
    if (!mimeTypeToExtension.ContainsKey(rowData[0]))
    {
        mimeTypeToExtension.Add(rowData[0], extensions);
    }

    foreach (var extension in extensions)
    {
        if (!extensionToMimeType.ContainsKey(extension))
        {
            extensionToMimeType.Add(extension, rowData[0]);
        }
    }

}

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

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