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

类别: CSharp.Net, 类库
标签: upload, .net, uploader, c#
摘要: 上传文件
正文:
1. x.aspx
2. cs/upload.cs

1. x.aspx
  1. <%@ Page Language="C#AutoEventWireup="True" %>
  2. <%@ Assembly src="cs/upload.cs" %>
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  4. <html xmlns="http://www.w3.org/1999/xhtml">
  5. <head>
  6. <meta http-equiv="Content-Typecontent="text/html; charset=utf-8" />
  7. <title>shawl.qiu template</title>
  8. </head>
  9. <body>
  10. <script runat="server">
  11.  void Page_Load(Object s, EventArgs e)
  12.  {
  13.   upload up=new upload();
  14.   
  15.   up.ext="7z,rar,zip,mp3,bmp,gif,jpg,jpeg,png,txt,swf";
  16.   up.debug=false;
  17.   up.item=5;                      // 声明显示多少个上传框
  18.   up.path="/uploads/";            // 上传目录;
  19.   up.goback_url=Request.Url+"";   // 上传完毕后返回的 URL
  20.   up.goback_second=5;             // 上传后返回间隔
  21.   up.interval=5;                  // 每次上传间隔, 单位秒
  22.   up.autorename=true;             // 自动重命名;
  23.   
  24.   // 声明 处理 所有 返回路径 的方法
  25.   //up.ReturnFilePath=new OneArgStringDelegate(GetPath);
  26.   
  27.   up.UploadPh=sqUpload;           // 声明显示上传控件的占位符
  28.   up.UploadBox();                 // 显示上传操作控件
  29.   
  30.   up=null;
  31.  }
  32.  
  33.  public void GetPath(String sPath)
  34.  {
  35.   System.Web.HttpContext.Current.Response.Write(sPath);
  36.  }
  37.  
  38. </script>
  39.  <form runat="server">
  40.   <asp:PlaceHolder id="sqUploadrunat="server" />
  41.  </form>
  42. </body>
  43. </html

2. cs/upload.cs
  1. using System;
  2. using System.Collections;
  3. using System.IO;
  4. using System.Text.RegularExpressions;
  5. using System.Web;
  6. using System.Web.UI;
  7. using System.Web.UI.WebControls;
  8. using System.Web.UI.HtmlControls;

  9. public delegate void OneArgStringDelegate(String Str);

  10. /*-----------------------------------------------------------------------------------*\
  11.  * shawl.qiu c# .net upload class v1.1
  12. \*-----------------------------------------------------------------------------------*/
  13. //---------------------------------------------------------------------begin class upload
  14. public class upload
  15. {
  16.  //-----------------------------------begin event
  17.  public upload()
  18.  {
  19.  }
  20.  
  21.  ~upload()
  22.  {
  23.  }
  24.  //-----------------------------------end event
  25.  
  26.  //-----------------------------------begin public constant
  27.  //-----------------------begin about
  28.  public const string auSubject="shawl.qiu c# .net upload class";
  29.  public const string auVersion="v1.1";
  30.  public const string au="shawl.qiu";
  31.  public const string auEmail="shawl.qiu@gmail.com";
  32.  public const string auBlog="http://blog.csdn.net/btbtd";
  33.  public const string auCreateDate="2007-1-30";
  34.  public const string auFirstUpdate="2007-2-8 v1.1";
  35.  //-----------------------end about
  36.  //-----------------------------------end public constant
  37.  
  38.  //-----------------------------------begin public variable
  39.  public Boolean debug=false;
  40.  public Boolean autorename=false;
  41.  
  42.  public String path="/uploads/";
  43.  public String ext="7z,rar,zip,mp3,bmp,gif,jpg,jpeg,png,txt,swf";
  44.  public String goback_url="?";
  45.  
  46.  public Int32 interval=10;
  47.  public Int32 goback_second=10;
  48.  public Int32 item=5;
  49.  public Int32 totalsize=1024*5;
  50.  public Int32 singlesize=1024;
  51.  
  52.  public PlaceHolder UploadPh;
  53.  
  54.  public OneArgStringDelegate ReturnFilePath;
  55.  
  56.  //-----------------------------------end public variable
  57.  
  58.  //-----------------------------------begin public method
  59.  
  60.  public void UploadBox()
  61.  {
  62.   if(UploadPh!=null)
  63.   {
  64.    UploadPh.Controls.Add(ErrorLabel);
  65.    UploadPh.Controls.Add(GobackLabel);
  66.    UploadPh.Controls.Add(UploadDetailsLabel);
  67.    
  68.    InfoLabel=new Label();
  69.    InfoLabel.Text="<ul>\n"+
  70.     "<li>允许上传的文件类型<b>: "+ext+"</b></li>\n"+
  71.     "<li>每次总上传大小最大为 <b>: "+totalsize+"kb</b>, 每文件最大为 <b>"+
  72.     singlesize+"kb</b>.</li>\n"+
  73.     "<li>每次上传时间间隔为<b>: "+interval+"</b>秒.</li>\n"+
  74.     "</ul>";
  75.      
  76.    UploadPh.Controls.Add(InfoLabel);
  77.     
  78.     LiteralBox=new Literal();
  79.     LiteralBox.Text="<ol>";
  80.     UploadPh.Controls.Add(LiteralBox);
  81.    
  82.    for(Int32 i=0; i<item; i++)
  83.    {
  84.     LiteralBox=new Literal();
  85.     LiteralBox.Text="<li>";
  86.     UploadPh.Controls.Add(LiteralBox);
  87.     
  88.     UpInputItem = new HtmlInputFile(); 
  89.     UploadPh.Controls.Add(UpInputItem);
  90.     
  91.     LiteralBox=new Literal();
  92.     LiteralBox.Text="</li>\n";
  93.     UploadPh.Controls.Add(LiteralBox);
  94.    }     
  95.     
  96.    LiteralBox=new Literal();
  97.    LiteralBox.Text="</br/>\n";
  98.    UploadPh.Controls.Add(LiteralBox);
  99.    
  100.    SubmitButton=new Button();
  101.    SubmitButton.Text="Upload now";
  102.    SubmitButton.Click+=new EventHandler(go);
  103.    SubmitButton.Attributes["onclick"]="javascript:return confirm('现在上传文件吗?')";
  104.    UploadPh.Controls.Add(SubmitButton);
  105.     
  106.    LiteralBox=new Literal();
  107.    LiteralBox.Text=" <input type=\"reset\" value=\"reset\""+
  108.    " onclick=\"return confirm('现在重置吗');\" />";
  109.    UploadPh.Controls.Add(LiteralBox);
  110.     
  111.    LiteralBox=new Literal();
  112.    LiteralBox.Text="</ol>\n";
  113.    UploadPh.Controls.Add(LiteralBox);
  114.   }
  115.  } // end public void UploadBox
  116.  
  117.  public void go(Object s, EventArgs e)
  118.  {
  119.   
  120.   if(HttpContext.Current.Session["sqUpFl"]==null)
  121.   {
  122.    HttpContext.Current.Session["sqUpFl"]=DateTime.Now;
  123.   }
  124.   
  125.   DateTime dtSession=DateTime.Parse(HttpContext.Current.Session["sqUpFl"]+"");

  126.   if(dtSession>DateTime.Now)
  127.   {
  128.    TimeSpan hasInterval=dtSession-DateTime.Now;
  129.    
  130.    finished("每次上传时间间隔为 "+interval+" 秒, 请稍候...",
  131.     hasInterval.Seconds, goback_url, GobackLabel);
  132.    goto End;
  133.   }
  134.   
  135.   //---------------------检测上传目录是否存在
  136.   String path_phs=HttpContext.Current.Server.MapPath(path);
  137.   if(!Directory.Exists(path_phs))
  138.   {
  139.    if(InfoLabel!=null)
  140.    {
  141.     InfoLabel.Text+="<h2>指定的上传目录不存在, 操作被取消.</h2>";
  142.    }
  143.    goto End;
  144.   }
  145.   
  146.   Int32 upTotal=HttpContext.Current.Request.ContentLength/1024;
  147.   Int32 total=HttpContext.Current.Request.Files.AllKeys.Length;
  148.   
  149.   ArrayList aUpsize=new ArrayList();
  150.   ArrayList aNoExt=new ArrayList();
  151.   ArrayList aNotAllowExt=new ArrayList();
  152.   ArrayList aFinished=new ArrayList();
  153.   
  154.   if(upTotal>totalsize) goto Upsize;
  155.    
  156.   for(Int32 i=0; i<total; i++)
  157.   {
  158.    System.Web.HttpPostedFile files=HttpContext.Current.Request.Files[i];
  159.    if(files.ContentLength>0)
  160.    { 
  161.     String flnm=Path.GetFileName(files.FileName);
  162.     String justnm=Path.GetFileNameWithoutExtension(files.FileName);
  163.     String justext=Path.GetExtension(files.FileName);
  164.     
  165.     String flph=path+justnm+justext;
  166.     String flph_phs=HttpContext.Current.Server.MapPath(flph);
  167.     
  168.     //-----------------------------------单文件超出限制大小
  169.     Int32 flSize=files.ContentLength/1024;
  170.     if(flSize>singlesize)
  171.     {
  172.      aUpsize.Add("文件: "+flnm+", 大小为: "+flSize+" kb.");
  173.      continue;
  174.     }    
  175.     
  176.     if(!Path.HasExtension(flnm))
  177.     {
  178.      aNoExt.Add("文件: "+flnm+", 没有扩展名.");
  179.      continue;
  180.     }
  181.     
  182.     String extTemp=Regex.Replace(justext,"^.","");
  183.     if(!Regex.IsMatch(ext, "\\b"+extTemp+"\\b", RegexOptions.IgnoreCase))
  184.     {
  185.      aNotAllowExt.Add("不允许上传的文件扩展: "+flnm);
  186.      continue;
  187.     }
  188.     
  189.     if(File.Exists(flph_phs)) //------------------已存在相同同名文件
  190.     {
  191.      if(autorename)
  192.      { 
  193.       Int32 iRename=1;
  194.       while(true)
  195.       {
  196.        String sNameTemp=HttpContext.Current.
  197.         Server.MapPath(path+justnm+"_"+(iRename++)+justext);
  198.        if(!File.Exists(sNameTemp))
  199.        {
  200.         flph_phs=sNameTemp;
  201.         goto SaveFile;
  202.        } // end if 3
  203.       } // end while
  204.      } // end if 2
  205.     } // end if 1
  206.     SaveFile:;
  207.      files.SaveAs(flph_phs);
  208.   
  209.      String flnmTemp=Path.GetFileName(flph_phs);
  210.      aFinished.Add("文件: "+flnmTemp+" 已上传.");
  211.      
  212.      allFilePath+=path+flnmTemp+",";
  213.      
  214.      HttpContext.Current.Session["sqUpFl"]=
  215.       DateTime.Now.AddSeconds(interval);
  216.    } // end if
  217.   } // end for
  218.   goto Report;
  219.   
  220.   Upsize:
  221.    ErrorLabel.Text+="<h2 style='text-align:center;'>上传大小超出限制, 已被终止.</h2>";
  222.    finished(goback_second+" 秒后返回, 还有 ", 
  223.     goback_second, goback_url, GobackLabel);
  224.   goto End;
  225.    
  226.   Report:
  227.    listAl("已上传文件 ", aFinished, UploadDetailsLabel);
  228.    listAl("单文件超出限制大小的有 ", aUpsize, UploadDetailsLabel);
  229.    listAl("没有文件扩展名的有 ", aNoExt, UploadDetailsLabel);
  230.    listAl("不允许上传的文件扩展有 ", aNotAllowExt, UploadDetailsLabel);
  231.   goto Finished;
  232.   
  233.   Finished:
  234.    finished("操作已完毕, "+goback_second+" 秒后返回, 还有 ", 
  235.     goback_second, goback_url, GobackLabel);
  236.   End: 
  237.    allFilePath=Regex.Replace(allFilePath,",$","");
  238.    
  239.    if(ReturnFilePath!=null)
  240.    { 
  241.     ReturnFilePath(allFilePath);
  242.    }
  243.  } // end go
  244.  //-----------------------------------end public method
  245.  
  246.  //-----------------------------------begin private variable
  247.  private String allFilePath="";
  248.  
  249.  private Label InfoLabel;
  250.  private Label GobackLabel=new Label();
  251.  private Label UploadDetailsLabel=new Label();
  252.  private Label ErrorLabel=new Label();
  253.  
  254.  private Literal LiteralBox;
  255.  
  256.  private Button SubmitButton;
  257.  
  258.  private HtmlInputFile UpInputItem;
  259.  //-----------------------------------end private variable
  260.  
  261.  //-----------------------------------begin private method
  262.  private void listAl(String sDetail, ArrayList oAl, Label UploadDetailsLabel)
  263.  {
  264.   if(oAl.Count>0)
  265.   {
  266.    UploadDetailsLabel.Text+="<ol><label>"+sDetail+"<b>"+
  267.     oAl.Count+"个</b>.</label>";
  268.    foreach(Object item in oAl)
  269.    {
  270.     UploadDetailsLabel.Text+="<li>"+item+"</li>";
  271.    }
  272.    UploadDetailsLabel.Text+="</ol><hr/>";
  273.   }
  274.  }
  275.  
  276.  private void finished(String sPrompt, Int32 iSecond, String sUrl, Label GobackLabel)
  277.  {
  278.   GobackLabel.Text+="<script type=\"text/javascript\">\n";
  279.   GobackLabel.Text+="//<![CDATA[\n";
  280.   GobackLabel.Text+=var temp=onload;\n";
  281.   GobackLabel.Text+=onload=function(){\n";
  282.   GobackLabel.Text+="  try{temp()}catch(e){}\n";
  283.   GobackLabel.Text+="  fTimer("+iSecond+",'timer', 10);\n";
  284.   GobackLabel.Text+=" }\n";
  285.   GobackLabel.Text+="  function fTimer(iTimestamp, sId, iMs){\n";
  286.   GobackLabel.Text+="  if(!(iTimestamp.constructor==Date)){\n";
  287.   GobackLabel.Text+="   var sqTimeStamp=new Date();\n";
  288.   GobackLabel.Text+="   sqTimeStamp.setSeconds(sqTimeStamp.getSeconds()+iTimestamp);\n";
  289.   GobackLabel.Text+="   iTimestamp=sqTimeStamp;\n";
  290.   GobackLabel.Text+="  }\n";
  291.   GobackLabel.Text+="    var tl=arguments.callee;\n";
  292.   GobackLabel.Text+="    if(typeof sId=='string'){\n";
  293.   GobackLabel.Text+="   var oEle=document.getElementById(sId);\n";
  294.   GobackLabel.Text+="  } else {\n";
  295.   GobackLabel.Text+="   var oEle=sId;\n";
  296.   GobackLabel.Text+="  }\n";
  297.   GobackLabel.Text+="  var dt=new Date();\n";
  298.   GobackLabel.Text+="  var iCk=((iTimestamp.getTime()-dt.getTime())/1000).toFixed(3);\n";
  299.   GobackLabel.Text+="  if(iCk<=0){\n";
  300.   GobackLabel.Text+="   oEle.innerHTML='00.000';\n";
  301.   GobackLabel.Text+="   return false;\n";
  302.   GobackLabel.Text+="  } else {\n";
  303.   GobackLabel.Text+="   oEle.innerHTML=iCk;\n";
  304.   GobackLabel.Text+="   var iTimer=setTimeout(function(){tl(iTimestamp, oEle, iMs)},iMs); \n";
  305.   GobackLabel.Text+="  }\n";
  306.   GobackLabel.Text+=" } // end function fTimer // shawl.qiu script\n";
  307.   GobackLabel.Text+="//]]>\n";
  308.   GobackLabel.Text+="</script>\n";

  309.   GobackLabel.Text+="<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />";
  310.   GobackLabel.Text+="<meta http-equiv=\"refresh\" content=\""+iSecond+";URL="+sUrl+"\">";
  311.   GobackLabel.Text+="<div style=\"display:table;width:100%;background-color:yellow!important;"+
  312.     "color:black!important;text-align:center!important;\">"+
  313.     sPrompt+", <span id='timer'>"+iSecond+"</span>秒 后返回.</div>";
  314.  }
  315.  //-----------------------------------end private method
  316. }
  317. //---------------------------------------------------------------------end class upload
  318.  
文章相关信息:
主题: shawl.qiu c# .net upload class v1.1
发表者: shawl.qiu
电子邮件: shawl.qiu@gmail.com
QQ: 908202921
MSN: btbtd@msn.com
Homepage: http://www.btbtd.org/
Blog: http://blog.csdn.net/btbtd/
发表日期: 2007-2-8 20:11:58
更新日期: 2007-2-8 20:11:58
来源引用: shawl.qiu CSharp DotNet 个人资料管理系统
引用本页: http://gi.2288.org/mod/code/display/Default.aspx?aid=261
关闭
Google
搜索WWW
搜索www.btbtd.org
搜索blog.csdn.net
Powered by shawl.qiu © 2008-2010 the shawl.qiu Javascript Kits
Copyright © 2008-2010 by shawl.qiu