shawl.qiu c# .net upload class v1.1

    技术2022-05-11  72

    shawl.qiu c# .net upload class v1.1 

     没什么好说的, .NET 干这个真太容易了...    这几天在写一个自动化画廊程序, 需要用到上传功能, 就重写了一下先前写的上传类,  使其使用更方便更简洁...  目录:  1. x.aspx  2. cs/upload.cs    下载:   http://files.myopera.com/btbtd/csharp/class/sq_csharp_upload_v1.1.7z    shawl.qiu  2007-02-08  http://blog.csdn.net/btbtd   1. x.aspx <%@ Page Language="C#AutoEventWireup="True" %> <%@ Assembly src="cs/upload.cs" %> <!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-Typecontent="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.ext="7z,rar,zip,mp3,bmp,gif,jpg,jpeg,png,txt,swf";   up.debug=false;   up.item=5;                      // 声明显示多少个上传框   up.path="/uploads/";            // 上传目录;   up.goback_url=Request.Url+"";   // 上传完毕后返回的 URL   up.goback_second=5;             // 上传后返回间隔   up.interval=5;                  // 每次上传间隔, 单位秒   up.autorename=true;             // 自动重命名;      // 声明 处理 所有 返回路径 的方法   //up.ReturnFilePath=new OneArgStringDelegate(GetPath);      up.UploadPh=sqUpload;           // 声明显示上传控件的占位符   up.UploadBox();                 // 显示上传操作控件      up=null;  }   public void GetPath(String sPath)  {   System.Web.HttpContext.Current.Response.Write(sPath);  }  </script>  <form runat="server">   <asp:PlaceHolder id="sqUploadrunat="server" />  </form> </body> </html>    2. cs/upload.cs using System; using System.Collections; using System.IO; using System.Text.RegularExpressions; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.HtmlControls; public delegate void OneArgStringDelegate(String Str); /*-----------------------------------------------------------------------------------*/  * shawl.qiu c# .net upload class v1.1 /*-----------------------------------------------------------------------------------*/ //---------------------------------------------------------------------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 class";  public const string auVersion="v1.1";  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";  public const string auFirstUpdate="2007-2-8 v1.1";  //-----------------------end about  //-----------------------------------end public constant   //-----------------------------------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 Int32 interval=10;  public Int32 goback_second=10;  public Int32 item=5;  public Int32 totalsize=1024*5;  public Int32 singlesize=1024;   public PlaceHolder UploadPh;   public OneArgStringDelegate ReturnFilePath;   //-----------------------------------end public variable   //-----------------------------------begin public method   public void UploadBox()  {   if(UploadPh!=null)   {    UploadPh.Controls.Add(ErrorLabel);    UploadPh.Controls.Add(GobackLabel);    UploadPh.Controls.Add(UploadDetailsLabel);        InfoLabel=new Label();    InfoLabel.Text="<ul>/n"+     "<li>允许上传的文件类型<b>: "+ext+"</b></li>/n"+     "<li>每次总上传大小最大为 <b>: "+totalsize+"kb</b>, 每文件最大为 <b>"+     singlesize+"kb</b>.</li>/n"+     "<li>每次上传时间间隔为<b>: "+interval+"</b>秒.</li>/n"+     "</ul>";          UploadPh.Controls.Add(InfoLabel);          LiteralBox=new Literal();     LiteralBox.Text="<ol>";     UploadPh.Controls.Add(LiteralBox);        for(Int32 i=0; i<item; i++)    {     LiteralBox=new Literal();     LiteralBox.Text="<li>";     UploadPh.Controls.Add(LiteralBox);          UpInputItem = new HtmlInputFile();      UploadPh.Controls.Add(UpInputItem);          LiteralBox=new Literal();     LiteralBox.Text="</li>/n";     UploadPh.Controls.Add(LiteralBox);    }              LiteralBox=new Literal();    LiteralBox.Text="</br/>/n";    UploadPh.Controls.Add(LiteralBox);        SubmitButton=new Button();    SubmitButton.Text="Upload now";    SubmitButton.Click+=new EventHandler(go);    UploadPh.Controls.Add(SubmitButton);         LiteralBox=new Literal();    LiteralBox.Text=" <input type=/"reset/" value=/"reset/" />";    UploadPh.Controls.Add(LiteralBox);         LiteralBox=new Literal();    LiteralBox.Text="</ol>/n";    UploadPh.Controls.Add(LiteralBox);   }  } // end public void UploadBox   public void go(Object s, EventArgs e)  {      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("每次上传时间间隔为 "+interval+" 秒, 请稍候...",     hasInterval.Seconds, goback_url, GobackLabel);    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>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=path+justnm+justext;     String flph_phs=HttpContext.Current.Server.MapPath(flph);          //-----------------------------------单文件超出限制大小     Int32 flSize=files.ContentLength/1024;     if(flSize>singlesize)     {      aUpsize.Add("文件: "+flnm+", 大小为: "+flSize+" kb.");      continue;     }              if(!Path.HasExtension(flnm))     {      aNoExt.Add("文件: "+flnm+", 没有扩展名.");      continue;     }          String extTemp=Regex.Replace(justext,"^.","");     if(!Regex.IsMatch(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(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+" 已上传.");            allFilePath+=path+flnmTemp+",";            HttpContext.Current.Session["sqUpFl"]=       DateTime.Now.AddSeconds(interval);    } // end if   } // end for   goto Report;      Upsize:    ErrorLabel.Text+="<h2 style='text-align:center;'>上传大小超出限制, 已被终止.</h2>";    finished(goback_second+" 秒后返回, 还有 ",      goback_second, goback_url, GobackLabel);   goto End;       Report:    listAl("已上传文件 ", aFinished, UploadDetailsLabel);    listAl("单文件超出限制大小的有 ", aUpsize, UploadDetailsLabel);    listAl("没有文件扩展名的有 ", aNoExt, UploadDetailsLabel);    listAl("不允许上传的文件扩展有 ", aNotAllowExt, UploadDetailsLabel);   goto Finished;      Finished:    finished("操作已完毕, "+goback_second+" 秒后返回, 还有 ",      goback_second, goback_url, GobackLabel);   End:     allFilePath=Regex.Replace(allFilePath,",$","");        if(ReturnFilePath!=null)    {      ReturnFilePath(allFilePath);    }  } // end go  //-----------------------------------end public method   //-----------------------------------begin private variable  private String allFilePath="";   private Label InfoLabel;  private Label GobackLabel=new Label();  private Label UploadDetailsLabel=new Label();  private Label ErrorLabel=new Label();   private Literal LiteralBox;   private Button SubmitButton;   private HtmlInputFile UpInputItem;  //-----------------------------------end private variable   //-----------------------------------begin private method  private void listAl(String sDetail, ArrayList oAl, Label UploadDetailsLabel)  {   if(oAl.Count>0)   {    UploadDetailsLabel.Text="<ol><label>"+sDetail+"<b>"+     oAl.Count+"个</b>.</label>";    foreach(Object item in oAl)    {     UploadDetailsLabel.Text+="<li>"+item+"</li>";    }    UploadDetailsLabel.Text+="</ol><hr/>";   }  }   private void finished(String sPrompt, Int32 iSecond, String sUrl, Label GobackLabel)  {   GobackLabel.Text+="<script type=/"text/javascript/">/n";   GobackLabel.Text+="//<![CDATA[/n";   GobackLabel.Text+=var temp=onload;/n";   GobackLabel.Text+=onload=function(){/n";   GobackLabel.Text+="  try{temp()}catch(e){}/n";   GobackLabel.Text+="  fTimer("+iSecond+",'timer', 10);/n";   GobackLabel.Text+=" }/n";   GobackLabel.Text+="  function fTimer(iTimestamp, sId, iMs){/n";   GobackLabel.Text+="  if(!(iTimestamp.constructor==Date)){/n";   GobackLabel.Text+="   var sqTimeStamp=new Date();/n";   GobackLabel.Text+="   sqTimeStamp.setSeconds(sqTimeStamp.getSeconds()+iTimestamp);/n";   GobackLabel.Text+="   iTimestamp=sqTimeStamp;/n";   GobackLabel.Text+="  }/n";   GobackLabel.Text+="    var tl=arguments.callee;/n";   GobackLabel.Text+="    if(typeof sId=='string'){/n";   GobackLabel.Text+="   var oEle=document.getElementById(sId);/n";   GobackLabel.Text+="  } else {/n";   GobackLabel.Text+="   var oEle=sId;/n";   GobackLabel.Text+="  }/n";   GobackLabel.Text+="  var dt=new Date();/n";   GobackLabel.Text+="  var iCk=((iTimestamp.getTime()-dt.getTime())/1000).toFixed(3);/n";   GobackLabel.Text+="  if(iCk<=0){/n";   GobackLabel.Text+="   oEle.innerHTML='00.000';/n";   GobackLabel.Text+="   return false;/n";   GobackLabel.Text+="  } else {/n";   GobackLabel.Text+="   oEle.innerHTML=iCk;/n";   GobackLabel.Text+="   var iTimer=setTimeout(function(){tl(iTimestamp, oEle, iMs)},iMs); /n";   GobackLabel.Text+="  }/n";   GobackLabel.Text+=" } // end function fTimer // shawl.qiu script/n";   GobackLabel.Text+="//]]>/n";   GobackLabel.Text+="</script>/n";   GobackLabel.Text+="<meta http-equiv=/"Content-Type/" content=/"text/html; charset=utf-8/" />";   GobackLabel.Text+="<meta http-equiv=/"refresh/" content=/""+iSecond+";URL="+sUrl+"/">";   GobackLabel.Text+="<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 } //---------------------------------------------------------------------end class upload    

    最新回复(0)