----------------------------------主体程序片段--------------------------------------------------------------------
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;
}
}