You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Microsoft.AspNetCore中从IFormFile获取文件扩展名

解决IFormFile获取文件扩展名的问题
  • 从文件名直接提取(最常用)
    利用IFormFile.FileName属性,通过路径工具类解析扩展名,代码示例:

    var fileExtension = Path.GetExtension(formFile.FileName).TrimStart('.').ToLowerInvariant();
    // 示例:文件名是"年度报表.xlsx"时,得到"xlsx"
    

    注:这种方式简单直接,虽然存在客户端篡改文件名的可能,但绝大多数业务场景下足够可靠。

  • 通过ContentType映射扩展名
    先维护一份标准ContentType与对应扩展名的映射字典,再根据IFormFile.ContentType匹配,代码示例:

    var contentTypeToExtension = new Dictionary<string, string>
    {
        { "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "xlsx" },
        { "application/pdf", "pdf" },
        { "image/png", "png" },
        { "application/msword", "doc" }
        // 根据业务需求添加更多类型映射
    };
    
    if (contentTypeToExtension.TryGetValue(formFile.ContentType, out var extension))
    {
        // 这里拿到的就是对应扩展名,比如"xlsx"或"pdf"
    }
    

    注:这种方式不受文件名篡改影响,但需要覆盖你业务中涉及的所有文件类型,避免遗漏。

  • 结合两种方式做兼容处理
    优先从文件名提取,当文件名无有效扩展名时,再用ContentType映射兜底,代码示例:

    string targetExtension = null;
    
    // 第一步:从文件名提取
    var nameExtension = Path.GetExtension(formFile.FileName).TrimStart('.').ToLowerInvariant();
    if (!string.IsNullOrWhiteSpace(nameExtension))
    {
        targetExtension = nameExtension;
    }
    // 第二步:ContentType映射兜底
    else
    {
        var contentTypeMap = new Dictionary<string, string>
        {
            { "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "xlsx" },
            { "application/pdf", "pdf" }
        };
        contentTypeMap.TryGetValue(formFile.ContentType, out targetExtension);
    }
    

    注:兼顾可靠性和兼容性,适合对文件类型验证要求较高的场景。

内容的提问来源于stack exchange,提问作者SDEV

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 05:06:28