c# .net 上传多个文件 By shawl.qiu

    技术2022-05-11  69

    shawl.qiu c# .net upload v1.0

    说明: 最近刚开始学习 .net, 俺本来是打算先从 JScript.net 下手... 不过在论坛发个帖子征求意见后...还是决定从.NET的主流语言 C#入手... 毕竟整个.NET Framework都是C#写的... 然后, 我发现 .NET最 重要的是它的 .NET Framework, 至于用什么语言应该差不多. 唉, 不说了, 目前这种一知半解的水平说多了会挨砖头... 目录: 1. upload.cs 2. x.aspx 调用演示 shawl.qiu 2007-01-30 http://blog.csdn.net/btbtd 内容: 1. upload.cs using System; using System.Collections; using System.Data; using System.IO; using System.Text.RegularExpressions; using System.Web; /*-----------------------------------------------------------------------------------*/  * shawl.qiu c# .net upload v1.0 /*-----------------------------------------------------------------------------------*/ //---------------------------------------------------------------------begin class upload public class upload {  //-----------------------------------begin event  public upload()  {  }   ~upload()  {  }  //-----------------------------------end event   //-----------------------------------begin public constant  //-----------------------begin about  public const string auSubject="shawl.qiu c# .net upload";  public const string auVersion="v1.0";  public const string au="shawl.qiu";  public const string auEmail="shawl.qiu@gmail.com";  public const string auBlog="http://blog.csdn.net/btbtd";  public const string auCreateDate="2007-1-30";  //-----------------------end about  //-----------------------------------end public constant   //-----------------------------------begin private constant  //-----------------------------------end private constant   //-----------------------------------begin public static method  //-----------------------------------end public static method   //-----------------------------------begin private static method  //-----------------------------------end private static method   //-----------------------------------begin public variable  public Boolean debug=false;  public Boolean autorename=false;   public String path="/uploads/";  public String ext="7z,rar,zip,mp3,bmp,gif,jpg,jpeg,png,txt,swf";  public String goback_url="?";  public String allFilePath="";   public Int32 interval=10;  public Int32 goback_second=10;  public Int32 item=5;  public Int32 totalsize=1024*5;  public Int32 singlesize=1024;  //-----------------------------------end public variable   //-----------------------------------begin public method  public void info(System.Web.UI.HtmlControls.HtmlContainerControl oSpan)  {   oSpan.InnerHtml="<ol>"+    "<li>允许上传的文件类型<b>: "+this.ext+"</b></li>"+    "<li>每次总上传大小最大为 <b>: "+this.totalsize+"kb</b>, 每文件最大为 <b>"+    this.singlesize+"kb</b>.</li>"+    "<li>每次上传时间间隔为<b>: "+this.interval+"</b>秒.</li>"+    "</ol>";  }   public void getItem(System.Web.UI.WebControls.Repeater rpt)  {   DataTable dt = new DataTable();   DataRow dr;   dt.Columns.Add(new DataColumn("id", typeof(Int32)));      for (int i = 0; i < this.item; i++)    {    dr = dt.NewRow();    dr[0] = i;    dt.Rows.Add(dr);   } // end for       rpt.DataSource=new DataView(dt);    rpt.DataBind();  } // end public void getItem   public void go()  {   if(HttpContext.Current.Session["sqUpFl"]==null)   {    HttpContext.Current.Session["sqUpFl"]=DateTime.Now;   }      DateTime dtSession=DateTime.Parse(HttpContext.Current.Session["sqUpFl"]+"");   if(dtSession>DateTime.Now)   {    TimeSpan hasInterval=dtSession-DateTime.Now;        finished("每次上传时间间隔为 "+this.interval+" 秒, 请稍候...",     hasInterval.Seconds, this.goback_url);    goto End;   }      //---------------------检测上传目录是否存在   String path_phs=HttpContext.Current.Server.MapPath(path);   if(!Directory.Exists(path_phs))   {    HttpContext.Current.     Response.Write("<h2>指定的上传目录不存在, 操作被取消.</h2>");    goto End;   }      Int32 upTotal=HttpContext.Current.Request.ContentLength/1024;   Int32 total=HttpContext.Current.Request.Files.AllKeys.Length;      ArrayList aUpsize=new ArrayList();   ArrayList aNoExt=new ArrayList();   ArrayList aNotAllowExt=new ArrayList();   ArrayList aFinished=new ArrayList();      if(upTotal>this.totalsize) goto Upsize;       for(Int32 i=0; i<total; i++)   {    System.Web.HttpPostedFile files=HttpContext.Current.Request.Files[i];    if(files.ContentLength>0)    {      String flnm=Path.GetFileName(files.FileName);     String justnm=Path.GetFileNameWithoutExtension(files.FileName);     String justext=Path.GetExtension(files.FileName);          String flph=this.path+justnm+justext;     String flph_phs=HttpContext.Current.Server.MapPath(flph);          //-----------------------------------单文件超出限制大小     Int32 flSize=files.ContentLength/1024;     if(flSize>this.singlesize)     {      aUpsize.Add("文件: "+flnm+", 大小为: "+flSize+" kb.");      continue;     }              if(!Path.HasExtension(flnm))     {      aNoExt.Add("文件: "+flnm+", 没有扩展名.");      continue;     }          String extTemp=Regex.Replace(justext,"^.","");     if(!Regex.IsMatch(this.ext, "//b"+extTemp+"//b", RegexOptions.IgnoreCase))     {      aNotAllowExt.Add("不允许上传的文件扩展: "+flnm);      continue;     }          if(File.Exists(flph_phs)) //------------------已存在相同同名文件     {      if(autorename)      {        Int32 iRename=1;       while(true)       {        String sNameTemp=HttpContext.Current.         Server.MapPath(this.path+justnm+"_"+(iRename++)+justext);        if(!File.Exists(sNameTemp))        {         flph_phs=sNameTemp;         goto SaveFile;        } // end if 3       } // end while      } // end if 2     } // end if 1     SaveFile:;      files.SaveAs(flph_phs);         String flnmTemp=Path.GetFileName(flph_phs);      aFinished.Add("文件: "+flnmTemp+" 已上传.");            this.allFilePath+=this.path+flnmTemp+",";            HttpContext.Current.Session["sqUpFl"]=       DateTime.Now.AddSeconds(this.interval);    } // end if   } // end for   goto Report;      Upsize:    HttpContext.Current.Response.Write("<h2>上传大小超出限制, 已被终止.</h2>");   goto End;       Report:    listAl("已上传文件 ", aFinished);    listAl("单文件超出限制大小的有 ", aUpsize);    listAl("没有文件扩展名的有 ", aNoExt);    listAl("不允许上传的文件扩展有 ", aNotAllowExt);   goto Finished;      Finished:    finished("操作已完毕", this.goback_second, this.goback_url);   End:     this.allFilePath=Regex.Replace(this.allFilePath,",$","");  } // end go  //-----------------------------------end public method   //-----------------------------------begin private variable  //-----------------------------------end private variable   //-----------------------------------begin private method  private void listAl(String sDetail, ArrayList oAl)  {   if(oAl.Count>0)   {    HttpContext.Current.Response.Write("<ol><label>"+sDetail+"<b>"+     oAl.Count+"个</b>.</label>");    foreach(Object item in oAl)    {     HttpContext.Current.Response.Write("<li>"+item+"</li>");    }    HttpContext.Current.Response.Write("</ol><hr/>");   }  }   private void finished(String sPrompt, Int32 iSecond, String sUrl)  {   HttpContext.Current.Response.Write("<script type=/"text/javascript/">/n");   HttpContext.Current.Response.Write("//<![CDATA[/n");   HttpContext.Current.Response.Write(" var temp=onload;/n");   HttpContext.Current.Response.Write(" onload=function(){/n");   HttpContext.Current.Response.Write("  try{temp()}catch(e){}/n");   HttpContext.Current.Response.Write("  fTimer("+iSecond+",'timer', 10);/n");   HttpContext.Current.Response.Write(}/n");   HttpContext.Current.Response.Write("  function fTimer(iTimestamp, sId, iMs){/n");   HttpContext.Current.Response.Write("  if(!(iTimestamp.constructor==Date)){/n");   HttpContext.Current.Response.Write("   var sqTimeStamp=new Date();/n");   HttpContext.Current.Response.Write("   sqTimeStamp.setSeconds(sqTimeStamp.getSeconds()+iTimestamp);/n");   HttpContext.Current.Response.Write("   iTimestamp=sqTimeStamp;/n");   HttpContext.Current.Response.Write("  }/n");   HttpContext.Current.Response.Write("    var tl=arguments.callee;/n");   HttpContext.Current.Response.Write("    if(typeof sId=='string'){/n");   HttpContext.Current.Response.Write("   var oEle=document.getElementById(sId);/n");   HttpContext.Current.Response.Write("  else {/n");   HttpContext.Current.Response.Write("   var oEle=sId;/n");   HttpContext.Current.Response.Write("  }/n");   HttpContext.Current.Response.Write("  var dt=new Date();/n");   HttpContext.Current.Response.Write("  var iCk=((iTimestamp.getTime()-dt.getTime())/1000).toFixed(3);/n");   HttpContext.Current.Response.Write("  if(iCk<=0){/n");   HttpContext.Current.Response.Write("   oEle.innerHTML='00.000';/n");   HttpContext.Current.Response.Write("   return false;/n");   HttpContext.Current.Response.Write("  else {/n");   HttpContext.Current.Response.Write("   oEle.innerHTML=iCk;/n");   HttpContext.Current.Response.Write("   var iTimer=setTimeout(function(){tl(iTimestamp, oEle, iMs)},iMs); /n");   HttpContext.Current.Response.Write("  }/n");   HttpContext.Current.Response.Write(} // end function fTimer // shawl.qiu script/n");   HttpContext.Current.Response.Write("//]]>/n");   HttpContext.Current.Response.Write("</script>/n");   HttpContext.Current.    Response.Write("<meta http-equiv=/"Content-Type/" content=/"text/html; charset=utf-8/" />");    HttpContext.Current.     Response.Write("<meta http-equiv=/"refresh/" content=/""+iSecond+";URL="+sUrl+"/">");   HttpContext.Current.    Response.Write("<div style=/"display:table;width:100%;background-color:yellow!important;"+     "color:black!important;text-align:center!important;/">"+     sPrompt+", <span id='timer'>"+iSecond+"</span>秒 后返回.</div>");  }  //-----------------------------------end private method   //-----------------------------------begin public property  //-----------------------------------end public property     //-----------------------------------begin private property  //-----------------------------------end private property } //---------------------------------------------------------------------end class upload 2. x.aspx 调用演示 <%@ Page Language="C#" src="cs/upload.cs" AutoEventWireup="True" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>shawl.qiu template</title> </head> <body> <script runat="server">  void Page_Load(Object s, EventArgs e)  {   upload up=new upload();   up.item=5;   up.info(spnInfo);   up.getItem(aspRpt);   up=null;  }   void btn_up(Object s, EventArgs e)  {   upload up=new upload();      up.debug=true;   up.path="/uploads/";           // 上传目录;   up.goback_url=Request.Url+"";  // 上传完毕后返回的 URL   up.goback_second=20;           // 上传后返回间隔   up.interval=20;                // 每次上传间隔, 单位秒   up.autorename=true;            // 自动重命名;   up.go();                       // 执行上传操作;    //Response.Write(up.allFilePath);// 返回已上传的所有文件路径, 以逗号(,)分隔.      up=null;  } </script>  <form runat="server">   <span id='spnReport' runat='server'></span>   <span id='spnInfo' runat='server'></span>   <ol>    <asp:Repeater id="aspRpt" runat="server">     <ItemTemplate>      <li><input type='file' runat='server' /></li>     </ItemTemplate>    </asp:Repeater>   </ol>     <li/><input type='submit' OnServerClick="btn_up" runat='server' />  </form> </body> </html>  

    最新回复(0)