天天看点

ASP.NET(C#)上传图片时防止木马的有效策略

internet上搜了一下别人的解决方案。不少人说用MIME来判断。自己也试了一下,如果用.NET的上传组件,确实可以。但如果用HTML基本的上传组件却不行(我是在HTML页中有上传组件,POST到后台另外的页面)。于是自己写了一段代码来检查上传文件是否真是图片文件。

前面两步检查属初级检查(当然,在前台用JS作了客户端的扩展名检查),如果通过再使用图片类检查,如果是真是图片 就能通过,否则不行(已经过测试)

protected bool isValidImage(System.Web.HttpPostedFile postedFile)

        {

            string sMimeType = postedFile.ContentType.ToLower();

            if (sMimeType.IndexOf("image/") < 0)

                return false;

            if (postedFile.ContentLength < 50)

                return false;

            try

            {

                System.Drawing.Image img = System.Drawing.Image.FromStream(postedFile.InputStream);

                if (img.Width * img.Height < 1)

                    return false;

                img.Dispose();

            }

            catch

            {

                return false;

            }            

            return true;

        }

转载于:https://www.cnblogs.com/dodui/archive/2011/12/02/2272819.html

c#