·您现在的位置: 云翼网络 >> 文章中心 >> 网站建设 >> 网站建设开发 >> ASP.NET网站开发 >> 判断图片上传

判断图片上传

作者:佚名      ASP.NET网站开发编辑:admin      更新时间:2022-07-23

不只是判断的扩展名,修改扩展名的也可判断。

 1 PRivate bool IsImage(string filePath)
 2         {
 3             Image image;
 4             try
 5             {
 6                 image = Image.FromFile(filePath);
 7                 image.Dispose();
 8                 return true;
 9             }
10             catch (Exception ex)
11             {
12                 return false;
13             }
14         }
View Code

 判断文件的头部

    /// <summary>
     /// 根据文件头判断上传的文件类型
     /// </summary>
    /// <param name="filePath">filePath是文件的完整路径       </param>
     /// <returns>返回true或false</returns>
    private bool IsPicture(string filePath)
    {
        try
        {
            FileStream fs = new FileStream(filePath, FileMode.Open, Fileaccess.Read);
            BinaryReader reader = new BinaryReader(fs);
            string fileClass;
            byte buffer;
            buffer = reader.ReadByte();
            fileClass = buffer.ToString();
            buffer = reader.ReadByte();
            fileClass += buffer.ToString();
            reader.Close();
            fs.Close();
            if (fileClass == "255216" || fileClass == "7173" || fileClass == "13780" || fileClass == "6677")

                  //255216是jpg;7173是gif;6677是BMP,13780是PNG;7790是exe,8297是rar 
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        catch
        {
            return false;
        }
    }
View Code