怎么样通过c# .net上传多个文件?
怎么样通过c# .net上传多个文件?
shawl.qiu c# .net upload v1.0
说明:最近刚开始学习 .net, 俺本来是打算先从 JScript.net 下手...
不过在CSDN论坛发个帖子征求意见后...还是决定从.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
- usingSystem;
- usingSystem.Collections;
- usingSystem.Data;
- usingSystem.IO;
- usingSystem.Text.RegularExpressions;
- usingSystem.Web;
- /*-----------------------------------------------------------------------------------*/
- *shawl.qiuc#.netuploadv1.0
- /*-----------------------------------------------------------------------------------*/
- //---------------------------------------------------------------------beginclassupload
- publicclassupload
- {
- //-----------------------------------beginevent
- publicupload()
- {
- }
- ~upload()
- {
- }
- //-----------------------------------endevent
- //-----------------------------------beginpublicconstant
- //-----------------------beginabout
- publicconststringauSubject="shawl.qiuc#.netupload";
- publicconststringauVersion="v1.0";
- publicconststringau="shawl.qiu";
- publicconststringauEmail="shawl.qiu@gmail.com";
- publicconststringauBlog="http://blog.csdn.net/btbtd";
- publicconststringauCreateDate="2007-1-30";
- //-----------------------endabout
- //-----------------------------------endpublicconstant
- //-----------------------------------beginprivateconstant
- //-----------------------------------endprivateconstant
- //-----------------------------------beginpublicstaticmethod
- //-----------------------------------endpublicstaticmethod
- //-----------------------------------beginprivatestaticmethod
- //-----------------------------------endprivatestaticmethod
- //-----------------------------------beginpublicvariable
- publicBooleandebug=false;
- publicBooleanautorename=false;
- publicStringpath="/uploads/";
- publicStringext="7z,rar,zip,mp3,bmp,gif,jpg,jpeg,png,txt,swf";
- publicStringgoback_url="?";
- publicStringallFilePath="";
- publicInt32interval=10;
- publicInt32goback_second=10;
- publicInt32item=5;
- publicInt32totalsize=1024*5;
- publicInt32singlesize=1024;
- //-----------------------------------endpublicvariable
- //-----------------------------------beginpublicmethod
- publicvoidinfo(System.Web.UI.HtmlControls.HtmlContainerControloSpan)
- {
- 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>";
- }
- publicvoidgetItem(System.Web.UI.WebControls.Repeaterrpt)
- {
- DataTabledt=newDataTable();
- DataRowdr;
- dt.Columns.Add(newDataColumn("id",typeof(Int32)));
- for(inti=0;i<this.item;i++)
- {
- dr=dt.NewRow();
- dr[0]=i;
- dt.Rows.Add(dr);
- }//endfor
- rpt.DataSource=newDataView(dt);
- rpt.DataBind();
- }//endpublicvoidgetItem
- publicvoidgo()
- {
- if(HttpContext.Current.Session["sqUpFl"]==null)
- {
- HttpContext.Current.Session["sqUpFl"]=DateTime.Now;
- }
- DateTimedtSession=DateTime.Parse(HttpContext.Current.Session["sqUpFl"]+"");
- if(dtSession>DateTime.Now)
- {
- TimeSpanhasInterval=dtSession-DateTime.Now;
- finished("每次上传时间间隔为"+this.interval+"秒,请稍候...",
- hasInterval.Seconds,this.goback_url);
- gotoEnd;
- }
- //---------------------检测上传目录是否存在
- Stringpath_phs=HttpContext.Current.Server.MapPath(path);
- if(!Directory.Exists(path_phs))
- {
- HttpContext.Current.
- Response.Write("<h2>指定的上传目录不存在,操作被取消.</h2>");
- gotoEnd;
- }
- Int32upTotal=HttpContext.Current.Request.ContentLength/1024;
- Int32total=HttpContext.Current.Request.Files.AllKeys.Length;
- ArrayListaUpsize=newArrayList();
- ArrayListaNoExt=newArrayList();
- ArrayListaNotAllowExt=newArrayList();
- ArrayListaFinished=newArrayList();
- if(upTotal>this.totalsize)gotoUpsize;
- for(Int32i=0;i<total;i++)
- {
- System.Web.HttpPostedFilefiles=HttpContext.Current.Request.Files[i];
- if(files.ContentLength>0)
- {
- Stringflnm=Path.GetFileName(files.FileName);
- Stringjustnm=Path.GetFileNameWithoutExtension(files.FileName);
- Stringjustext=Path.GetExtension(files.FileName);
- Stringflph=this.path+justnm+justext;
- Stringflph_phs=HttpContext.Current.Server.MapPath(flph);
- //-----------------------------------单文件超出限制大小
- Int32flSize=files.ContentLength/1024;
- if(flSize>this.singlesize)
- {
- aUpsize.Add("文件:"+flnm+",大小为:"+flSize+"kb.");
- continue;
- }
- if(!Path.HasExtension(flnm))
- {
- aNoExt.Add("文件:"+flnm+",没有扩展名.");
- continue;
- }
- StringextTemp=Regex.Replace(justext,"^.","");
- if(!Regex.IsMatch(this.ext,"//b"+extTemp+"//b",RegexOptions.IgnoreCase))
- {
- aNotAllowExt.Add("不允许上传的文件扩展:"+flnm);
- continue;
- }
- if(File.Exists(flph_phs))//------------------已存在相同同名文件
- {
- if(autorename)
- {
- Int32iRename=1;
- while(true)
- {
- StringsNameTemp=HttpContext.Current.
- Server.MapPath(this.path+justnm+"_"+(iRename++)+justext);
- if(!File.Exists(sNameTemp))
- {
- flph_phs=sNameTemp;
- gotoSaveFile;
- }//endif3
- }//endwhile
- }//endif2
- }//endif1
- SaveFile:;
- files.SaveAs(flph_phs);
- StringflnmTemp=Path.GetFileName(flph_phs);
- aFinished.Add("文件:"+flnmTemp+"已上传.");
- this.allFilePath+=this.path+flnmTemp+",";
- HttpContext.Current.Session["sqUpFl"]=
- DateTime.Now.AddSeconds(this.interval);
- }//endif
- }//endfor
- gotoReport;
- Upsize:
- HttpContext.Current.Response.Write("<h2>上传大小超出限制,已被终止.</h2>");
- gotoEnd;
- Report:
- listAl("已上传文件",aFinished);
- listAl("单文件超出限制大小的有",aUpsize);
- listAl("没有文件扩展名的有",aNoExt);
- listAl("不允许上传的文件扩展有",aNotAllowExt);
- gotoFinished;
- Finished:
- finished("操作已完毕",this.goback_second,this.goback_url);
- End:
- this.allFilePath=Regex.Replace(this.allFilePath,",$","");
- }//endgo
- //-----------------------------------endpublicmethod
- //-----------------------------------beginprivatevariable
- //-----------------------------------endprivatevariable
- //-----------------------------------beginprivatemethod
- privatevoidlistAl(StringsDetail,ArrayListoAl)
- {
- if(oAl.Count>0)
- {
- HttpContext.Current.Response.Write("<ol><label>"+sDetail+"<b>"+
- oAl.Count+"个</b>.</label>");
- foreach(ObjectiteminoAl)
- {
- HttpContext.Current.Response.Write("<li>"+item+"</li>");
- }
- HttpContext.Current.Response.Write("</ol><hr/>");
- }
- }
- privatevoidfinished(StringsPrompt,Int32iSecond,StringsUrl)
- {
- HttpContext.Current.Response.Write("<scripttype=/"text/javascript/">/n");
- HttpContext.Current.Response.Write("//<![CDATA[/n");
- HttpContext.Current.Response.Write("vartemp=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("functionfTimer(iTimestamp,sId,iMs){/n");
- HttpContext.Current.Response.Write("if(!(iTimestamp.constructor==Date)){/n");
- HttpContext.Current.Response.Write("varsqTimeStamp=newDate();/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("vartl=arguments.callee;/n");
- HttpContext.Current.Response.Write("if(typeofsId=='string'){/n");
- HttpContext.Current.Response.Write("varoEle=document.getElementById(sId);/n");
- HttpContext.Current.Response.Write("}else{/n");
- HttpContext.Current.Response.Write("varoEle=sId;/n");
- HttpContext.Current.Response.Write("}/n");
- HttpContext.Current.Response.Write("vardt=newDate();/n");
- HttpContext.Current.Response.Write("variCk=((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("returnfalse;/n");
- HttpContext.Current.Response.Write("}else{/n");
- HttpContext.Current.Response.Write("oEle.innerHTML=iCk;/n");
- HttpContext.Current.Response.Write("variTimer=setTimeout(function(){tl(iTimestamp,oEle,iMs)},iMs);/n");
- HttpContext.Current.Response.Write("}/n");
- HttpContext.Current.Response.Write("}//endfunctionfTimer//shawl.qiuscript/n");
- HttpContext.Current.Response.Write("//]]>/n");
- HttpContext.Current.Response.Write("</script>/n");
- HttpContext.Current.
- Response.Write("<metahttp-equiv=/"Content-Type/"content=/"text/html;charset=utf-8/"/>");
- HttpContext.Current.
- Response.Write("<metahttp-equiv=/"refresh/"content=/""+iSecond+";URL="+sUrl+"/">");
- HttpContext.Current.
- Response.Write("<divstyle=/"display:table;width:100%;background-color:yellow!important;"+
- "color:black!important;text-align:center!important;/">"+
- sPrompt+",<spanid='timer'>"+iSecond+"</span>秒后返回.</div>");
- }
- //-----------------------------------endprivatemethod
- //-----------------------------------beginpublicproperty
- //-----------------------------------endpublicproperty
- //-----------------------------------beginprivateproperty
- //-----------------------------------endprivateproperty
- }
- //---------------------------------------------------------------------endclassupload
- <%@PageLanguage="C#"src="cs/upload.cs"AutoEventWireup="True"%>
- <!DOCTYPEhtmlPUBLIC"-//W3C//DTDXHTML1.0Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
- <htmlxmlns="http://www.w3.org/1999/xhtml">
- <head>
- <metahttp-equiv="Content-Type"content="text/html;charset=utf-8"/>
- <title>shawl.qiutemplate</title>
- </head>
- <body>
- <scriptrunat="server">
- voidPage_Load(Objects,EventArgse)
- {
- uploadup=newupload();
- up.item=5;
- up.info(spnInfo);
- up.getItem(aspRpt);
- up=null;
- }
- voidbtn_up(Objects,EventArgse)
- {
- uploadup=newupload();
- 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>
- <formrunat="server">
- <spanid='spnReport'runat='server'></span>
- <spanid='spnInfo'runat='server'></span>
- <ol>
- <asp:Repeaterid="aspRpt"runat="server">
- <ItemTemplate>
- <li><inputtype='file'runat='server'/></li>
- </ItemTemplate>
- </asp:Repeater>
- </ol>
- <li/><inputtype='submit'OnServerClick="btn_up"runat='server'/>
- </form>
- </body>
- </html>