代码之家  ›  专栏  ›  技术社区  ›  Ashish Gupta Shiva

ASP.NET如何检查文件类型,而不考虑扩展名

  •  2
  • Ashish Gupta Shiva  · 技术社区  · 14 年前

    如果有人将任何文件(Excel除外)的扩展名重命名为XLS和XLSX(请不要问我为什么:—(),我需要检查其有效性(如果这仍然是有效的Excel文件)。我使用的是mime类型,但不起作用。我错过什么了吗?

    const string excel2007MimeType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
    const string excel2003MimeType = "application/vnd.ms-excel";
    
      string excelExtention = string.Empty;
                excelExtention = System.IO.Path.GetExtension(myFilePath.PostedFile.FileName).ToLower();
                string mimeType = myFilePath.PostedFile.ContentType;
                Response.Write("mime type" + mimeType + Environment.NewLine);
                if( 
                     (
                        !(excelExtention == ".xls" && mimeType == excel2003MimeType)
                        ||
                        !(excelExtention == ".xlsx" && mimeType == excel2007MimeType)
                     )
                  )
                {
                    Response.Write ("only excel file is permitted");
                }
    

    我将JPG文件重命名为XLSX文件并上载。如果我输出变量mimetype,它的值是“application/vnd.openxmlformats officecondument.spreadsheetml.sheet”。我不知道为什么,因为内容不是Excel文件。它是一个形象。

    2 回复  |  直到 14 年前
        1
  •  3
  •   Kieren Johnstone    14 年前

    为此,您需要尝试使用Excel库或Excel COM对象本身打开它。不幸的是,微软在服务器环境中不支持Office COM对象自动化。

    您可以只读取文件的第一部分并检查二进制签名,但要支持所有可能的XLS版本,则需要做大量的工作;.xslx文件只是包含文档的几个部分的zip文件。

    希望有帮助。

        2
  •  3
  •   Steve Danner    14 年前

    你可以一直使用 Excel OleDB Database driver 尝试打开一个 OleDbConnection 反对它。