Kin*_*xit 24
在aspx页面中:
<asp:FileUpload ID="FileUpload1" runat="server" />
Run Code Online (Sandbox Code Playgroud)
在codebehind(c#)中:
string contentType = FileUpload1.PostedFile.ContentType
Run Code Online (Sandbox Code Playgroud)
小智 13
如果重命名和上传文件,上面的代码将不会提供正确的内容类型.
请使用此代码
using System.Runtime.InteropServices;
[DllImport("urlmon.dll", CharSet = CharSet.Unicode, ExactSpelling = true, SetLastError = false)]
static extern int FindMimeFromData(IntPtr pBC,
[MarshalAs(UnmanagedType.LPWStr)] string pwzUrl,
[MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.I1, SizeParamIndex = 3)] byte[] pBuffer,
int cbSize,
[MarshalAs(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)
{
Marshal.FreeCoTaskMem(mimeout);
return "";
}
string mime = Marshal.PtrToStringUni(mimeout);
Marshal.FreeCoTaskMem(mimeout);
return mime.ToLower();
}
Run Code Online (Sandbox Code Playgroud)
Ric*_*lay 10
虽然在描述HTTP请求的内容类型可能不正确的情况下,他的说法是正确的,但我不认为非托管调用的编组是值得的.如果你需要回退到扩展到mimetype映射,只需从System.Web.MimeMapping.cctor"借用"代码(使用Reflector).这种字典方法绰绰有余,不需要本机调用.