【问题标题】:How should I detect the MIME type of an uploaded file in ASP.NET?我应该如何在 ASP.NET 中检测上传文件的 MIME 类型?
【发布时间】:2010-09-10 00:35:51
【问题描述】:

人们通常如何使用 ASP.NET 检测上传文件的 MIME 类型?

【问题讨论】:

    标签: asp.net types mime


    【解决方案1】:

    如果文件被重命名和上传,上面的代码将不会给出正确的内容类型。

    请使用此代码

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

    【讨论】:

      【解决方案2】:

      虽然 aneesh 说 HTTP 请求的内容类型可能不正确是正确的,但我认为非托管调用的编组是不值得的。如果您需要回退到扩展到 mimetype 的映射,只需从 System.Web.MimeMapping.cctor 中“借用”代码(使用 Reflector)。这种字典方法绰绰有余,不需要本地调用。

      【讨论】:

      • 此时System.Web.MimeMapping.GetMimeMapping()函数是公共的,可以直接调用。
      【解决方案3】:

      在aspx页面中:

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

      在代码隐藏 (c#) 中:

      string contentType = FileUpload1.PostedFile.ContentType
      

      【讨论】:

        猜你喜欢
        • 2011-06-03
        • 2012-01-26
        • 2014-02-20
        • 2011-11-15
        • 2012-04-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-08-09
        相关资源
        最近更新 更多