Reputation: 15139
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");
}
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.
Upvotes: 2
Views: 3617
Reputation: 22158
You could always use the Excel OleDB Database driver and try to open an OleDbConnection against it.
Upvotes: 3
Reputation: 42003
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.
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.
Hope that helps.
Upvotes: 3