.Net编程

asp.net上传文件检测类型

日期:2015-06-28 00:00:00 来源: IT猫扑网

  上传文件检测类型到目前为止我只看到过3种,第一种是检测文件的后缀名;第二种是检测文件的头部编码,不同类型文件的头部编码是不一样的(比如255216是jpg,7173是gif,6677是BMP,13780是PNG,7790是exe,8297是rar等);第三中是检测文件的MIME内容类型。这篇文章代码多有参考网络,特此说明。

  前台文件:三种方法的前台文件是一样的.

  view source <http://www.cnblogs.com/feelboy/archive/2010/08/19/1803175.html>

  print <http://www.cnblogs.com/feelboy/archive/2010/08/19/1803175.html>>

  1<%@ Page Language="C#" AutoEventWireup="true"   CodeFile="Default.aspx.cs" Inherits="_Default" %>
http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd%22%3E
>" target=_blank><http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd>">
xmlns="http://www.w3.org/1999/xhtml%22%C2%A0%3E
>" target=_blank>http://www.w3.org/1999/xhtml" >

     无标题页


    


    

  
   OnClick="btn_upload_Click" Text="上传" />
    

    


  后台文件:

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

  01public partial class _Default : System.Web.UI.Page

  02{

  03     protected void btn_upload_Click(object sender, EventArgs e)

  04     {

  05   Boolean fileOk = false;

  06   string path = Server.MapPath("~/images/");

  07   //判断是否已经选取文件

  08   if (FileUpload1.HasFile)

  09   {

  10 //取得文件的扩展名,并转换成小写

  11 string fileExtension = System.IO.Path.GetExtension(FileUpload1.FileName).ToLower();

  12 //限定只能上传jpg和gif图片

  13 string[] allowExtension = { ".jpg", ".gif" };

  14 //对上传的文件的类型进行一个个匹对

  15 for (int i = 0; i < allowExtension.Length; i++)

  16 {

  17     if (fileExtension == allowExtension[i])

  18     {

  19   fileOk = true;

  20   break;

  21     }

  22 }

  23   }

  24   else

  25   {

  26 Response.Write("");

  27   }

  28   //如果扩展名符合条件,则上传

  29   if (fileOk)

  30   {

  31 FileUpload1.PostedFile.SaveAs(path + FileUpload1.FileName);

  32 Response.Write("");

  33   }

  34     }

  35}

  第二种方法,可以实现真正意义上的文件类型判断。

  01public partial class _Default : System.Web.UI.Page

  02{

  03      protected void btn_upload_Click(object sender, EventArgs e)

  04     {

  05   try

  06   {

  07 //判断是否已经选取文件

  08 if (FileUpload1.HasFile)

  09 {

  10     if (IsAllowedExtension(FileUpload1))

  11     {

  12   string path = Server.MapPath("~/images/");

  13   FileUpload1.PostedFile.SaveAs(path + FileUpload1.FileName);

  14   Response.Write("");

  15     }

  16     else

  17     {

  18   Response.Write("");

  19    

相关文章

相关下载

网友评论

我要评论...
    没有更早的评论了
    取消