当前位置: 首页 > 科技观察

ASP.NET大文件下载的实现思路和代码

时间:2023-03-12 07:48:33 科技观察

当我们的网站需要支持大文件的下载时,如果不加以控制,可能会导致用户在访问下载页面时出现无响应,从而导致浏览器坠毁。你可以参考下面的代码来避免这个问题。usingSystem;namespaceWebApplication1{publicpartialclassDownloadFile:System.Web.UI.Page{protectedvoidPage_Load(objectsender,EventArgse){System.IO.StreamiStream=null;//Buffertoread10Kbytesinchunk:byte[]buffer=newByte[10000];//Lengthofthefile:intlength;//Totalbytestoread.longdataToRead;//Identifythefiletodownloadincludingitspath.stringfilepath=Server.MapPath("/")+"./Files/TextFile1.txt";//Identifythefilename.stringfilename=System.IO.Path.GetFileName(filepath);尝试{//Openthefile.iStream=newSystem.IO.FileStream(filepath,System.IO.FileMode.Open,System.IO.FileAccess.Read,System.IO.FileShare.Read);//Totalbytestoread.dataToRead=iStream.Length;响应。Clear();Response.ClearHeaders();Response.ClearContent();Response.ContentType="text/plain";//设置文件类型Response.AddHeader("Content-Length",dataToRead.ToString());Response.AddHeader("Content-Disposition","attachment;filename="+filename";//Readthebytes.while(dataToRead>0){//Verifythattheclientisconnected.if(Response.IsClientConnected){//Readthedatainbuffer.length=iStream.Read(buffer,0,10000);//将数据写入当前输出流.Response.OutputStream.Write(buffer,0,length);//FlushthedatatotheHTMLoutput.Response.Flush();buffer=newByte[10000];dataToRead=dataToRead-length;}else{//PreventinfiniteloopifuserdisconnectsdataToRead=-1;}}}catch(Exceptionex){//Traptheerror,ifany.Response.Write("Error:"+ex.Message);}finally{if(iStream!=null){//Closethefile.iStream.Close();}Response.End();}}}}关于这段代码一些注意事项:1.通过将数据分成更小的部分来获取数据,然后将其移动到输出流以供下载2.根据正在下载的文件类型指定Response.ContentType。(参考OSChina的这个网址可以找到大部分文件类型的对照表:http://tool.oschina.net/commons)3.记得每次写完response后调用Response.Flush()4.在循环下载过程中使用Response.IsClientConnected判断可以帮助程序尽快发现连接是否正常。如果不正常,可以尽快放弃下载,释放占用的服务器资源。5、下载结束后,需要调用Response.End()来保证当前线程能够在结束时终止。原文链接:http://www.codeceo.com/article/asp-net-big-file.html