Har*_*run 5 c# asp.net validation content-type file-upload
我需要检查上传文件是否是csv而不检查文件扩展名.如果将非csv文件重命名为".csv"扩展名,则使用filecontent属性也无法有效地找到该类型.我需要防止这种事情发生.
任何人请建议一种通过阅读标题信息来查找内容类型的方法.
我尝试了以下代码,它从文件中读取前 256 个字节,并使用内部 dll (urlmon.dll) 返回文件的 mime 类型。
使用 System.Runtime.InteropServices;...
[DllImport(@"urlmon.dll", CharSet = CharSet.Auto)]
private extern static System.UInt32 FindMimeFromData(
    System.UInt32 pBC,
    [MarshalAs(UnmanagedType.LPStr)] System.String pwzUrl,
    [MarshalAs(UnmanagedType.LPArray)] byte[] pBuffer,
    System.UInt32 cbSize,
    [MarshalAs(UnmanagedType.LPStr)] System.String pwzMimeProposed,
    System.UInt32 dwMimeFlags,
    out System.UInt32 ppwzMimeOut,
    System.UInt32 dwReserverd
);
public string getMimeFromFile(string filename)
{
    if (!File.Exists(filename))
        throw new FileNotFoundException(filename + " not found");
    byte[] buffer = new byte[256];
    using (FileStream fs = new FileStream(filename, FileMode.Open))
    {
        if (fs.Length >= 256)
            fs.Read(buffer, 0, 256);
        else
            fs.Read(buffer, 0, (int)fs.Length);
    }
    try
    {
        System.UInt32 mimetype;
        FindMimeFromData(0, null, buffer, 256, null, 0, out mimetype, 0);
        System.IntPtr mimeTypePtr = new IntPtr(mimetype);
        string mime = Marshal.PtrToStringUni(mimeTypePtr);
        Marshal.FreeCoTaskMem(mimeTypePtr);
        return mime;
    }
    catch (Exception e)
    {
        return "unknown/unknown";
    }
}
但请检查不同浏览器中的类型,因为不同浏览器中的 mimetype 可能不同。
即使您更改了扩展名,这也会给出准确的 mimetype...
| 归档时间: | 
 | 
| 查看次数: | 2068 次 | 
| 最近记录: |