以图片为例子。在上传图片的时候,使用Fiddler抓取

C# 防止content-type修改后上传恶意文件

C# 防止content-type修改后上传恶意文件

C# 防止content-type修改后上传恶意文件

C# 防止content-type修改后上传恶意文件

 

C# 防止content-type修改后上传恶意文件

 

 通过js判断文件类型是不安全的,所以通过后台来判断,代码如下:

if (Request.Files.Count > 0)
                    {
                        HttpPostedFile file0 = Request.Files[0];
                        Stream stream;
                        byte[] fileByte = new byte[2];
                        stream = file0.InputStream;
                        stream.Read(fileByte, 0, 2);//contentLength,还是取前两位  
                        stream.Close();
                        string fileFlag = "";
                        if (fileByte != null && fileByte.Length > 0)//图片数据是否为空  
                        {
                            fileFlag = fileByte[0].ToString() + fileByte[1].ToString();
                        }
                        string[] fileTypeStr = { "255216", "7173", "6677", "13780" };//对应的图片格式jpg,gif,bmp,png
                        if (fileTypeStr.Contains(fileFlag))
                        {
                            file0.SaveAs(Server.MapPath("~/" + file0.FileName));
                        }
                        else
                        {
                            Response.Write("图片格式不正确:" + fileFlag);
                        }
                    }

这样就可以有效的防止修改了上传文件的content-type后上传文件到服务器了。如有不对之处,请留言提意见!

 

C# 防止content-type修改后上传恶意文件C# 防止content-type修改后上传恶意文件C# 防止content-type修改后上传恶意文件

 

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-09-15
  • 2022-12-23
  • 2021-11-02
  • 2021-04-26
  • 2021-07-08
  • 2021-05-01
猜你喜欢
  • 2022-12-23
  • 2021-07-30
  • 2021-08-12
  • 2021-09-22
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案