一、安全性比较低,把文本文件1.txt改成1.jpg照样可以上传,但其实现方法容易理解,实现也简单,所以网上很多还是采取这种方法。

    Boolean fileOk = false;
              string path = Server.MapPath("~/images/");
              //判断是否已经选取文件
              if (FileUpload1.HasFile)
              {
                  //取得文件的扩展名,并转换成小写
                  string fileExtension = System.IO.Path.GetExtension(FileUpload1.FileName).ToLower();
                  //限定只能上传jpg和gif图片
                  string[] allowExtension = { ".jpg", ".gif" };
                  //对上传的文件的类型进行一个个匹对
                  int j = 0;
                  for (int i = 0; i < allowExtension.Length; i++)
                  {
                      if (fileExtension == allowExtension[i])
                      {
                          fileOk = true;
                          return;
                      }
                      else
                      {
                          j++;
                      }
                  }
                  if (j > 0)
                  {
                      Response.Write("<script>alert('文件格式不正确');</script>");
                      return;
                  }
              }
              else
              {
                  Response.Write("<script>alert('你还没有选择文件');</script>");
                  return;
              }
              //如果扩展名符合条件,则上传
              if (fileOk)
              {
                  FileUpload1.PostedFile.SaveAs(path + FileUpload1.FileName);
                  Response.Write("<script>alert('上传成功');</script>");
              }

  二、不检测文件后缀而是检测文件MIME内容类型。

    Boolean fileOk = false;
               string path = Server.MapPath("~/images/");
               //判断是否已经选取文件
               if (FileUpload1.HasFile)
               {
                   //取得文件MIME内容类型
                   string type = this.FileUpload1.PostedFile.ContentType.ToLower();
                   if (type.Contains("image"))    //图片的MIME类型为"image/xxx",这里只判断是否图片。
                   {
                       fileOk = true;
     
                   }
                   else
                   {
                       Response.Write("<script>alert('格式不正确')</script>");
                   }
               }
               else
               {
                   Response.Write("<script>alert('你还没有选择文件');</script>");
               }
               //如果扩展名符合条件,则上传
               if (fileOk)
               {
                   FileUpload1.PostedFile.SaveAs(path + FileUpload1.FileName);
                   Response.Write("<script>alert('上传成功');</script>");
               }