ASP.NET中人们通常如何检测上传文件的MIME类型?
在 aspx 页面中:
<asp:FileUpload ID="FileUpload1" runat="server" />
在代码后台(C#)中:
string contentType = FileUpload1.PostedFile.ContentType
如果文件被重命名并上传,上述代码将无法提供正确的内容类型。
请使用以下代码:
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();
}
虽然Aneesh所说的HTTP请求的内容类型可能不正确,但我认为为非托管调用编排代码并不值得。如果需要退回到扩展名与MIME类型映射,请从System.Web.MimeMapping.cctor中“借用”代码(使用Reflector)。这种字典方法已经足够,并且不需要调用本地代码。
在 ASP.NET Core 中从文件获取 MIME 类型
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;
}