ASP.NET如何检查的文件类型的类型不论扩展 [英] ASP.NET how to check type of the file type irrespective of extension

查看:130
本文介绍了ASP.NET如何检查的文件类型的类型不论扩展的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果有人重命名的任何文件的扩展名(比Excel的除外)为XLS和XLSX(请不要问我为什么:-(),我需要检查其有效性(如果这仍然是一个有效的Excel文件)。我我使用MIME类型和它不工作。我缺少什么?

If somebody renames the extension of any file (other than excel) to xls and xlsx (please dont ask me why :-( ), I need to check for its validity (if that is still a valid excel file). I am using mime type and Its not working. Am I missing anything?

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文件并上传。如果我打印变量MIME类型,其值为应用/ vnd.openxmlformats-officedocument.s preadsheetml.sheet。我不知道为什么,因为内容不是一个Excel文件。它的图像。

I rename a jpg file to xlsx file and upload. If I print out variable mimetype, Its value is "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet". I am not sure why because the content is not an excel file. Its an image.

推荐答案

要做到这一点你需要尝试使用Excel库,或Excel COM对象本身将其打开。微软不支持在服务器环境办公室COM对象自动化,很遗憾。

To do that you'd need to attempt to open it using an Excel library, or Excel COM object itself. Microsoft doesn't support Office COM object automation in a server environment, unfortunately.

您可以只读取文件的第一部分,然后检查二进制签名,但将是大量的工作,以支持所有可能的XLS版本;和.XSLX文件只是ZIP包含文档文件的几个部分。

You could just read the first part of the file and check for a binary signature, but it would be a lot of work to support all possible XLS versions; and .XSLX files are simply ZIP files containing the document in several parts.

希望有所帮助。

这篇关于ASP.NET如何检查的文件类型的类型不论扩展的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆