ASP.NET中Path.GetExtension在Chrome失效,如何获取真实文件扩展名?
Chrome下获取上传文件真实扩展名的解决方案
我之前也遇到过这个问题,Chrome在文件上传时的文件名处理逻辑确实和IE、Firefox不一样——它会返回带C:\fakepath\的伪路径,偶尔还会因为安全限制导致System.IO.Path.GetExtension无法正确解析扩展名。下面给你几个实用的解决方案:
方案1:通过MIME类型映射扩展名(最可靠)
这个方法不依赖文件名,直接从HTTP请求的ContentType获取文件类型,再映射到对应的扩展名,完全规避Chrome的文件名问题:
// 获取文件的MIME类型 string contentType = fpdDocument.PostedFile.ContentType; // 建立MIME类型与扩展名的映射字典,覆盖你需要支持的文件类型 var mimeToExtensionMap = new Dictionary<string, string> { {"application/zip", ".zip"}, {"text/plain", ".txt"}, {"application/vnd.ms-excel", ".xls"}, {"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", ".xlsx"}, {"application/msword", ".doc"}, {"application/vnd.openxmlformats-officedocument.wordprocessingml.document", ".docx"}, {"image/jpeg", ".jpg"}, {"image/png", ".png"} }; // 匹配对应的扩展名 string fileExtension = mimeToExtensionMap.ContainsKey(contentType) ? mimeToExtensionMap[contentType] : string.Empty;
优点:不受文件名干扰,安全可靠;缺点:需要提前配置好所有需要支持的MIME类型。
方案2:手动解析文件名(兼容伪路径)
如果还是想用文件名来获取扩展名,可以先提取纯文件名(去掉Chrome的C:\fakepath\前缀),再手动解析最后一个点后的部分:
string fullFileName = fpdDocument.PostedFile.FileName; // 提取纯文件名,自动去掉伪路径前缀 string pureFileName = System.IO.Path.GetFileName(fullFileName); // 查找最后一个点的位置,提取扩展名 int dotPosition = pureFileName.LastIndexOf('.'); string fileExtension = dotPosition >= 0 ? pureFileName.Substring(dotPosition) : string.Empty;
这个方法能处理Chrome返回的伪路径,因为Path.GetFileName会自动忽略前面的路径部分,只保留文件名本身,再提取扩展名就没问题了。
方案3:双重验证(兼顾准确性与兼容性)
把上面两种方法结合起来,先用文件名解析扩展名,再用MIME类型交叉验证,确保结果准确:
string fullFileName = fpdDocument.PostedFile.FileName; string pureFileName = System.IO.Path.GetFileName(fullFileName); int dotPosition = pureFileName.LastIndexOf('.'); string extFromFileName = dotPosition >= 0 ? pureFileName.Substring(dotPosition).ToLower() : string.Empty; // 获取MIME类型并映射扩展名 string contentType = fpdDocument.PostedFile.ContentType; var mimeToExtensionMap = new Dictionary<string, string> { {"application/zip", ".zip"}, {"text/plain", ".txt"}, {"application/vnd.ms-excel", ".xls"}, {"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", ".xlsx"}, {"application/msword", ".doc"}, {"application/vnd.openxmlformats-officedocument.wordprocessingml.document", ".docx"}, {"image/jpeg", ".jpg"}, {"image/png", ".png"} }; string extFromMime = mimeToExtensionMap.ContainsKey(contentType) ? mimeToExtensionMap[contentType] : string.Empty; // 优先使用MIME类型对应的扩展名,若不存在则用文件名解析的结果 string finalExtension = string.IsNullOrEmpty(extFromMime) ? extFromFileName : extFromMime;
这种方式既避免了文件名的异常情况,又保证了扩展名的准确性,适合对文件类型要求严格的场景。
内容的提问来源于stack exchange,提问作者Papun Sahoo
相关产品推荐
相关产品推荐

