標籤:
當我們的網站需要支援下載大檔案時,如果不做控制可能會導致使用者在訪問下載頁面時發生無響應,使得瀏覽器崩潰。可以參考如下代碼來避免這個問題。
關於此代碼的幾點說明:
1. 將資料分成較小的部分,然後將其移動到輸出資料流以供下載,從而擷取這些資料。
2. 根據下載的檔案類型來指定 Response.ContentType 。(這個網址可以找到大部分檔案類型的對照表:http://tool.oschina.net/commons)
3. 在每次寫完response時記得調用 Response.Flush()
4. 在迴圈下載的過程中使用 Response.IsClientConnected 這個判斷可以協助程式儘早發現串連是否正常。若不正常,可以及早的放棄下載,以釋放所佔用的伺服器資源。
5. 在下載結束後,需要調用 Response.End() 來保證當前線程可以在最後被終止掉。
1 using System; 2 3 namespace WebApplication1 4 { 5 public partial class DownloadFile : System.Web.UI.Page 6 { 7 protected void Page_Load(object sender, EventArgs e) 8 { 9 System.IO.Stream iStream = null;10 11 // Buffer to read 10K bytes in chunk:12 byte[] buffer = new Byte[10000];13 14 // Length of the file:15 int length;16 17 // Total bytes to read.18 long dataToRead;19 20 // Identify the file to download including its path.21 string filepath = Server.MapPath("/") +"./Files/TextFile1.txt";22 23 // Identify the file name.24 string filename = System.IO.Path.GetFileName(filepath);25 26 try27 {28 // Open the file.29 iStream = new System.IO.FileStream(filepath, System.IO.FileMode.Open,30 System.IO.FileAccess.Read, System.IO.FileShare.Read);31 32 // Total bytes to read.33 dataToRead = iStream.Length;34 35 Response.Clear();36 Response.ClearHeaders();37 Response.ClearContent();38 Response.ContentType = "text/plain"; // Set the file type39 Response.AddHeader("Content-Length", dataToRead.ToString());40 Response.AddHeader("Content-Disposition", "attachment; filename=" + filename);41 42 // Read the bytes.43 while (dataToRead > 0)44 {45 // Verify that the client is connected.46 if (Response.IsClientConnected)47 {48 // Read the data in buffer.49 length = iStream.Read(buffer, 0, 10000);50 51 // Write the data to the current output stream.52 Response.OutputStream.Write(buffer, 0, length);53 54 // Flush the data to the HTML output.55 Response.Flush();56 57 buffer = new Byte[10000];58 dataToRead = dataToRead - length;59 }60 else61 {62 // Prevent infinite loop if user disconnects63 dataToRead = -1;64 }65 }66 }67 catch (Exception ex)68 {69 // Trap the error, if any.70 Response.Write("Error : " + ex.Message);71 }72 finally73 {74 if (iStream != null)75 {76 //Close the file.77 iStream.Close();78 }79 80 Response.End();81 }82 }83 }84 }
參考文獻: http://support2.microsoft.com/kb/812406
ASP.Net 下載大檔案的實現