·您现在的位置: 云翼网络 >> 文章中心 >> 网站建设 >> 网站建设开发 >> ASP.NET网站开发 >> ASP.NET 大文件下载的实现思路及代码

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

作者:佚名      ASP.NET网站开发编辑:admin      更新时间:2022-07-23

asp.net 大文件下载的实现思路及代码

 文件下载是一个网站最基本的功能,ASP.NET网站的文件下载功能实现也很简单,但是如果遇到大文件的下载而不做特殊处理的话,那将会出现不可预料的后果。本文就基于ASP.NET提供大文件下载的实现思路及代码。

  当我们的网站需要支持下载大文件时,如果不做控制可能会导致用户在访问下载页面时发生无响应,使得浏览器崩溃。可以参考如下代码来避免这个问题。

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970using System;namespace Webapplication1{public partial class DownloadFile : System.Web.UI.Page{PRotected void Page_Load(object sender, EventArgs e){System.IO.Stream iStream = null;// Buffer to read 10K bytes in chunk:byte[] buffer = new Byte[10000];// Length of the file:int length;// Total bytes to read.long dataToRead;// Identify the file to download including its path.string filepath = Server.MapPath("/") +"./Files/TextFile1.txt";// Identify the file name.string filename = System.IO.Path.GetFileName(filepath);try{// Open the file.iStream = new System.IO.FileStream(filepath, System.IO.FileMode.Open,System.IO.Fileaccess.Read, System.IO.FileShare.Read);// Total bytes to read.dataToRead = iStream.Length;Response.Clear();Response.ClearHeaders();Response.ClearContent();Response.ContentType = "text/plain"; // Set the file typeResponse.AddHeader("Content-Length", dataToRead.ToString());Response.AddHeader("Content-Disposition", "attachment; filename=" + filename);// Read the bytes.while (dataToRead > 0){// Verify that the client is connected.if (Response.IsClientConnected){// Read the data in buffer.length = iStream.Read(buffer, 0, 10000);// Write the data to the current output stream.Response.OutputStream.Write(buffer, 0, length);// Flush the data to the HTML output.Response.Flush();buffer = new Byte[10000];dataToRead = dataToRead - length;}else{// Prevent infinite loop if user disconnectsdataToRead = -1;}}}catch (Exception ex){// Trap the error, if any.Response.Write("Error : " + ex.Message);}finally{if (iStream != null){//Close the file.iStream.Close();}
  • 上一篇文章:
  • 下一篇文章: