上传图片验证

----------------------------------主体程序片段--------------------------------------------------------------------

 string fileNameExt = postFile.FileName.Substring(postFile.FileName.LastIndexOf('.')).ToLower();
                            if (!pic.CheckFileExt(fileNameExt))
                            {
                                context.Response.Write("图片格式不正确!");
                                return;
                            }
                            int upFileLength = postFile.ContentLength;
                            ///判断图片是否是有效的图片格式,做初步判断
                            if (upFileLength <= 0 || !postFile.ContentType.Contains("image/"))
                            {
                                context.Response.Write("不是有效的图片!");
                                return;
                            }
                            byte[] FileArray = new Byte[upFileLength];
                            Stream fileStream = postFile.InputStream;
                            fileStream.Read(FileArray, 0, upFileLength);
                            if (!pic.Isimg(FileArray))
                            {
                                context.Response.Write("不是有效的图片!");
                                return;
                            }

--------------------------------验证函数----------------------------------------------------------------------

/// <summary>
        /// 检测图片类型
        /// </summary>
        /// <param name="_fileExt"></param>
        /// <returns>正确返回True</returns>
        public bool CheckFileExt(string _fileExt)
        {
            string[] allowExt = new string[] { ".gif", ".jpg", ".jpeg", ".png", ".bmp" };
            for (int i = 0; i < allowExt.Length; i++)
            {
                if (allowExt[i].ToLower() == _fileExt) { return true; }
            }
            return false;
        }
        /// <summary>
        /// 判断是否是真正的图片格式,有时候把文件扩展名修改成图片格式来伪装,用此法便可判断
        /// </summary>
        /// <param name="buffer"></param>
        /// <returns></returns>
        public bool Isimg(byte[] buffer)
        {
            string fileClass;
            fileClass = buffer[0].ToString() + buffer[1].ToString();
            if (fileClass == "255216" || fileClass == "7173" || fileClass == "6677" || fileClass == "13780")//255216是jpg;7173是gif;6677是BMP,13780是PNG;7790是exe,8297是rar
            {
                return true;
            }
            else
            {
                return false;
            }
        }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值