zoukankan      html  css  js  c++  java
  • ASP.NET FileUpload 上传文件类型验证

    验证的核心方法:

    public static bool IsAllowedExtension(FileUpload hifile)
            {
                //原方法是这样的,会提示找不到文件
                //System.IO.FileStream fs = new System.IO.FileStream(hifile.PostedFile.FileName, System.IO.FileMode.Open, System.IO.FileAccess.Read);
                //System.IO.BinaryReader r = new System.IO.BinaryReader(fs); 
                var buf = new byte[hifile.PostedFile.InputStream.Length];
                hifile.PostedFile.InputStream.Read(buf, 0, (int)hifile.PostedFile.InputStream.Length);
                Stream strem = new MemoryStream(buf);
                System.IO.BinaryReader r = new System.IO.BinaryReader(strem);
                string fileclass = "";
                //这里的位长要具体判断. 
                byte buffer;
                try
                {
                    buffer = r.ReadByte();
                    fileclass = buffer.ToString();
                    buffer = r.ReadByte();
                    fileclass += buffer.ToString();
                }
                catch
                {
                }
                r.Close();
                if (fileclass == "255216" || fileclass == "7173")//说明255216是jpg;7173是gif;6677是BMP,13780是PNG;7790是exe,8297是rar 
                {
                    return true;
                }
                else
                {
                    return false;
                }
            } 

    编码的数值:

    JPG = 255216,
            GIF = 7173,
            BMP = 6677,
            PNG = 13780,
            SWF = 6787,
            RAR = 8297,
            ZIP = 8075,
            _7Z = 55122,
            TXT = 102100,
            PDF = 3780,
            DOC = 208207,
            XLSX = 8075,
            XLS = 208207,
            CHM = 7384
            XML = 6063,
            HTML = 6033,
            ASPX = 239187,
            CS = 117115,
            JS = 119105,
            SQL = 255254,

    当然,如果不知道可以自己导入文件进行实验,得到对应的数字。

    前端可以通过asp.net 自带的RegularExpressionValidator控件进行验证

    <div style="margin-top:15px;">选择文件:&nbsp;&nbsp;<asp:FileUpload ID="fileUpload" runat="server" />
        <asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ControlToValidate="fileUpload" ErrorMessage="file type incorrect" ValidationExpression="^.*?.(xls|xlsx)$"></asp:RegularExpressionValidator>
        </div>

    参考:
    http://developer.51cto.com/art/201305/396627.htm
    http://bbs.csdn.net/topics/210082978

  • 相关阅读:
    POJ 2513 Colored Sticks 字典树 + 并查集 + 欧拉通路
    管理收尾往往是项目经理经常忽略的过程
    一个十人开发团队的人员安排
    GridView的RowCreated与RowDataBound事件区别
    全局程序集缓存(GAC)
    Aspose.Cells 使用整理
    Difference between Assembly and Namespace
    Ltib 应用初步
    setsocketopt() usage
    ARM地址空间
  • 原文地址:https://www.cnblogs.com/tylertang/p/6433277.html
Copyright © 2011-2022 走看看