When our site needs to support downloading large files, if you do not control may cause users to access the download page when the unresponsive, causing the browser to crash. You can avoid this problem by referring to the following code.
Using System;namespace webapplication1{public partial class DownloadFile:System.Web.UI.Page {protected VO ID 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, 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 (); } response.end (); } } }}
A few notes about this code:
1. Divide the data into smaller parts and then move it to the output stream for download to get the data.
2. Specify Response.ContentType according to the file type you downloaded. (refer to this URL for Oschina to find the table of most file types: http://tool.oschina.net/commons)
3. Remember to call Response.Flush () every time you finish writing Response.
Implementation ideas and codes for ASP. NET large File download