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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM