根据二进制流判断上传文件类型是否合法(非扩展名)

来源:互联网 发布:php域名和ip授权 编辑:程序博客网 时间:2024/06/08 06:01
 代码:
/* 根据二进制流判断上传文件类型是否合法(非扩展名) */using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Web.UI.WebControls;using System.IO;namespace FrameWork{    public class FileValidation    {        public static bool IsAllowedExtension(FileUpload fu, FileExtension[] fileEx)        {            int fileLen = fu.PostedFile.ContentLength;            byte[] imgArray = new byte[fileLen];            fu.PostedFile.InputStream.Read(imgArray, 0, fileLen);            MemoryStream ms = new MemoryStream(imgArray);            System.IO.BinaryReader br = new BinaryReader(ms);            string fileclass = "";            byte buffer;            try             {                buffer = br.ReadByte();                fileclass = buffer.ToString();                buffer = br.ReadByte();                fileclass += buffer.ToString();            }            catch(Exception ex)            {                throw ex;            }            br.Close();            ms.Close();            foreach (FileExtension fe in fileEx)            {                if (Int32.Parse(fileclass) == (int)fe)                    return true;            }            return false;        }            }    public enum FileExtension    {        JPG = 255216,        GIF= 7173,        BMP=6677,        PNG=13780,        EXE_DLL = 7790,        RAR = 8297,        XML = 6063,        HTML = 6033,        ASPX = 239187,        CS = 117115,        JS = 119105,        TXT = 210187,        SQL = 255254,    }}

调用:

 FileExtension[] fe = { FileExtension.GIF, FileExtension.JPG };            if (FileValidation.IsAllowedExtension(fUploadArticle, fe))            {                //格式正确                Alert("格式正确!");            }            else            {                Alert("格式不正确!");            }


 

原创粉丝点击