2008-09-17 5 views

답변

22

: 숨김 (c 번호)에

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

: 파일 이름이 업로드되면

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

이 코드를 사용하십시오, 나는 관리되지 않는 호출에 대한 마샬링 가치가 있다고 생각하지 않는다 그것. Extension-to-Mimetype 매핑으로 되돌아 가야한다면 System.Web.MimeMapping.cctor (Reflector 사용)에서 코드를 "빌려"사용해야합니다. 이 사전 접근 방식은 충분하지 않으며 기본 호출을 필요로하지 않습니다.

+1

이 시점에서 System.Web.MimeMapping.GetMimeMapping() 함수는 public이며 직접 호출 할 수 있습니다. –