How should I detect the MIME type of an uploaded file in ASP.NET?

How do people usually detect the MIME type of an uploaded file using ASP.NET?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

in the aspx page:

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

in the codebehind (c#):
string contentType = FileUpload1.PostedFile.ContentType

Method 2

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

Please use this code for that

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

Method 3

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.

Method 4

Get MIME type from a file in ASP.NET Core

public string GetMimeType(string filePath)
{
    var provider = new FileExtensionContentTypeProvider();

    if (!provider.TryGetContentType(filePath, out var contentType))
        contentType = "application/octet-stream"; // fallback: unknown binary type
        
    return contentType;
}


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x