文件下載是一個(gè)網(wǎng)站最基本的功能,ASP.NET網(wǎng)站的文件下載功能實(shí)現(xiàn)也很簡(jiǎn)單,但是如果遇到大文件的下載而不做特殊處理的話,那將會(huì)出現(xiàn)不可預(yù)料的后果。本文就基于ASP.NET提供大文件下載的實(shí)現(xiàn)思路及代碼。
當(dāng)我們的網(wǎng)站需要支持下載大文件時(shí),如果不做控制可能會(huì)導(dǎo)致用戶在訪問(wèn)下載頁(yè)面時(shí)發(fā)生無(wú)響應(yīng),使得瀏覽器崩潰??梢詤⒖既缦麓a來(lái)避免這個(gè)問(wèn)題。
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();
}
|