Click here to Skip to main content
15,887,683 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
There is a case in file upload,I have a image file and I am uploading that one is fine, and in other case have change the extension of .exe to png /jpeg , then how can we validate that file in this case.

What I have tried:

HttpPostedFile file = FileUpload1.PostedFile;
       byte[] document = new byte[file.ContentLength];
       file.InputStream.Read(document, 0, file.ContentLength);
       System.UInt32 mimetype;
       FindMimeFromData(0, null, document, 256, null, 0, out mimetype, 0);
       System.IntPtr mimeTypePtr = new IntPtr(mimetype);
       string mime = Marshal.PtrToStringUni(mimeTypePtr);
       Marshal.FreeCoTaskMem(mimeTypePtr);

       if (mime == "application/pdf")
       {
           // upload the File because file is valid // and checking other file type
           Response.Write("This is Valid File");
       }
       else
       {
           //  file is Invalid
           Response.Write("This is Invalid File");

       }
Posted
Comments
Mike Hankey 10-Sep-18 9:24am    
https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types
Take a look at this site for a list of mime types.
MadMyche 10-Sep-18 13:12pm    
In the cases where it is not working, what is "FindMimeFromData" returning?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900