图片上传双重验证

文件上传是我们在开发中常用的功能,通常是只验证文件的后缀是否符合要求有,这样就给不良用心的人留下了后门。所以今天给大家附上一个双重验证的例子。

#region ------------上传图片----------------
        private bool UploadPic(HttpPostedFile file, ref string msg, int seed)
        {
            if (file.ContentLength > 0)
            {
                string fileName = file.FileName;
                string extension = Path.GetExtension(fileName);

                Stream stream = file.InputStream;
                MemoryStream copy = new MemoryStream();
                try
                {
                    //复制一份用于检查大小,格式,宽高
                    CopyStream(stream, copy);
                    if (copy.Length > 4000000) //4M
                    {
                        msg = "图片文件太大";
                        return false;
                    }

                    int iWidth = 0;
                    int iHeight = 0;
                    if (!HasThisForamt(extension) || !CheckImageFile(copy, out iWidth, out iHeight))
                    {
                        msg = "请选择正确的图片(.gif|.png|.jpg|.bmp|.jpeg)";
                        return false;
                    }

                    string strDir = System.Web.HttpContext.Current.Server.MapPath("upload/" + LoginInfo.UserName.Substring(0, 1) + "/" + LoginInfo.UserId);
                    if (!Directory.Exists(strDir))
                    {
                        Directory.CreateDirectory(strDir);
                    }
                    Random rnd = new Random(seed);
                    int num = rnd.Next(5000, 10000);
                    string strFilePath = strDir + "\\" + LoginInfo.UserId + "_" + num.ToString() + extension;
                    msg = LoginInfo.UserName.Substring(0, 1) + "/" + LoginInfo.UserId + "/" + LoginInfo.UserId + "_" + num.ToString() + extension;
                    file.SaveAs(strFilePath);
                }
                catch (Exception ex)
                {
                    Qlyx.Common.Utils.WriteErrorLog(ex.Message + ex.StackTrace);
                    msg = "很抱歉上传失败了, 请稍后再试吧";
                    return false;
                }
                finally
                {
                    if (stream != null)
                    {
                        stream.Close();
                    }
                    if (copy != null)
                    {
                        copy.Close();
                    }
                }
                return true;
            }
            else
            {
                msg = "请选择证件图片";
                return false;
            }
        }

        private bool HasThisForamt(string strExtension)
        {
            string ImageFormats = ".gif|.png|.jpg|.bmp|.jpeg";
            if (ImageFormats.ToLower().IndexOf(strExtension.ToLower()) >= 0)
            {
                return true;
            }
            return false;
        }

        private void CopyStream(Stream input, Stream output)
        {
            int iBufferSize = 4096;
            byte[] buf = new byte[iBufferSize];
            while (true)
            {
                int iRead = input.Read(buf, 0, buf.Length);
                if (iRead > 0)
                {
                    output.Write(buf, 0, iRead);
                }
                else
                {
                    return;
                }
            }

        }

        private bool CheckImageFile(Stream stream, out int iWidth, out int iHeight)
        {
            iWidth = 0;
            iHeight = 0;
            bool IsImage = false;

            System.IO.BinaryReader reader = null;
            string bx = " ";
            byte buffer;
            try
            {
                stream.Seek(0, SeekOrigin.Begin);
                reader = new System.IO.BinaryReader(stream);
                buffer = reader.ReadByte();
                bx = buffer.ToString();
                buffer = reader.ReadByte();
                bx += buffer.ToString();
                /*
                7173 gif
                255216 jpg
                13780 png
                6677 bmp
                7790 exe dll
                00 ani--ico--cur
                7783 
                255254 --ini
                9146 -- ini
                5866 
                6395 hlp
                8269 reg
                70105 log
                205168 
                7384 chm
                5549 txt
                117115 txt
                5450 txt
                5666 psd
                255254 rdp
                10056 bt种子
                8297 rar
                64101 bat 
                */
                if (bx == "7173" || bx == "255216" || bx == "13780" || bx == "6677")
                {
                    IsImage = true;
                    System.Drawing.Image img = System.Drawing.Image.FromStream(stream);
                    iWidth = img.Width;
                    iHeight = img.Height;
                    img.Dispose();
                }
            }
            catch (Exception ex)
            {
                Qlyx.Common.Utils.WriteErrorLog(ex.Message + ex.StackTrace);
            }
            finally
            {
                if (reader != null)
                    reader.Close();
            }
            return IsImage;
        }
        #endregion

 

posted @ 2013-10-24 17:49  程序新青年  阅读(260)  评论(0编辑  收藏
============================================================================== 青春匆匆,很多人都有自己的座右铭,鞭策自己前进,当没看到座右铭的时候又忘了自己要干什么,就这样天天立志,志天天立,最终还是那个初出茅庐的小菜鸟。从现在开始,慢慢去改掉懒惰的习惯。慢慢去加强学习,直到慢慢成功。==============================================================================