文件下載是一個網站最基本的功能,ASP.NET網站的文件下載功能實現也很簡單,但是如果遇到大文件的下載而不做特殊處理的話,那將會出現不可預料的后果。本文就基于ASP.NET提供大文件下載的實現思路及代碼。
當我們的網站需要支持下載大文件時,如果不做控制可能會導致用戶在訪問下載頁面時發生無響應,使得瀏覽器崩潰。可以參考如下代碼來避免這個問題。
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970 | using 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 type
Response.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 disconnects
dataToRead = -1;
}
}
}
catch (Exception ex)
{
// Trap the error, if any.
Response.Write( "Error : " + ex.Message);
}
finally
{
if (iStream != null )
{
//Close the file.
iStream.Close();
}
|