views:

4118

answers:

3

How do people usually detect mime type once file uploaded using asp.net?

+2  A: 

in the aspx page:

<asp:FileUpload ID="FileUpload1" runat="server" />

in the codebehind (c#):

string contentType = FileUpload1.PostedFile.ContentType
kinjal
+2  A: 

The above code will not give correct content type if file is renamed and uploaded.

Please use this code for that

[System.Runtime.InteropServices.DllImport("urlmon.dll", CharSet = System.Runtime.InteropServices.CharSet.Unicode, ExactSpelling = true, SetLastError = false)] static extern int FindMimeFromData(IntPtr pBC, [System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.LPWStr)] string pwzUrl, [System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.LPArray, ArraySubType = System.Runtime.InteropServices.UnmanagedType.I1, SizeParamIndex = 3)] byte[] pBuffer, int cbSize, [System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.LPWStr)] string pwzMimeProposed, int dwMimeFlags, out IntPtr ppwzMimeOut, int dwReserved);

   public static string getMimeFromFile(HttpPostedFile file)
   {
       IntPtr mimeout;

       int MaxContent = (int)file.ContentLength;
       if (MaxContent > 4096) MaxContent = 4096;

       byte[] buf = new byte[MaxContent];
       file.InputStream.Read(buf, 0, MaxContent);
       int result = FindMimeFromData(IntPtr.Zero, file.FileName, buf, MaxContent, null, 0, out mimeout, 0);

       if (result != 0)
       {
           System.Runtime.InteropServices.Marshal.FreeCoTaskMem(mimeout);
           return "";
       }

       string mime = System.Runtime.InteropServices.Marshal.PtrToStringUni(mimeout);
       System.Runtime.InteropServices.Marshal.FreeCoTaskMem(mimeout);

       return mime.ToLower();
   }
A: 

While aneesh is correct in saying that the content type of the HTTP request may not be correct, I don't think that the marshalling for the unmanaged call is worth it. If you need to fall back to extension-to-mimetype mappings, just "borrow" the code from System.Web.MimeMapping.cctor (use Reflector). This dictionary approach is more than sufficient and doesn't require the native call.

Richard Szalay