前面两步检查属初级检查(当然,在前台用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;
}
还有另外一种方式
//真正是否真的为图片
public static bool IsAllowedExtension(FileUpload hifile)
{
FileStream fs = new FileStream(hifile.PostedFile.FileName,FileMode.Open,FileAccess.Read);
BinaryReader r = new BinaryReader(fs);
string fileclass = "";
byte buffer;
try
{
buffer = r.ReadByte();
fileclass = buffer.ToString();
buffer = r.ReadByte();
fileclass += buffer.ToString();
}
catch { }
r.Close();
fs.Close();
//说明255216是jpg;7173是gif;6677是BMP,13780是PNG;7790是exe,8297是rar,|| fileclass=="13780"||fileclass=="6677"
if (fileclass == "255216" || fileclass == "7173")
{
return true;
}
else
{
return false;
}
}
本文介绍了一种前后端结合的图片验证方法,包括客户端扩展名检查、服务端MIME类型及尺寸检查,以及通过读取文件头判断图片真实性的方法。
861

被折叠的 条评论
为什么被折叠?



