C# .net 判断上传文件是否是图片,防止木马上传


方法一:用image对象判断是否为图片

 1       /// 判断文件是否为图片
 2       /// </summary>
 3       /// <param name="path">文件的完整路径</param>
 4       /// <returns>返回结果</returns>
 5     public Boolean IsImage(string path)
 6     {
 7         try
 8         {
 9             System.Drawing.Image img = System.Drawing.Image.FromFile(path);
10             return true;
11         }
12         catch (Exception e)
13         {
14             return false;
15         }
16     } 

方法二,判断文件头

  /// 根据文件头判断上传的文件类型
     /// </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;
        }
    }

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM