2008-09-17 36 views

回答

22

在aspx頁面:

<asp:FileUpload ID="FileUpload1" runat="server" /> 
在代碼隱藏(C#)

string contentType = FileUpload1.PostedFile.ContentType 
12

如果文件被重命名,並上傳上面的代碼不會給正確的內容類型。

雖然aneesh是說,HTTP請求的內容類型可能不正確,請正確使用此代碼爲

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(); 
} 
10

,我不認爲非託管呼叫編組值得它。如果您需要回退到擴展到MIME類型的映射,只需從System.Web.MimeMapping.cctor中「借用」代碼(使用Reflector)。這種字典方式綽綽有餘,不需要本地電話。

+1

此時,System.Web.MimeMapping.GetMimeMapping()函數是公共的,可以直接調用。 – 2014-10-20 16:43:25

相關問題