当我们的网站需要支持下载大文件时,如果不做控制可能会导致用户在访问下载页面时发生无响应,使得浏览器崩溃。可以参考如下代码来避免这个问题。
关于此代码的几点说明:
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 try 27 { 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 type 39 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 else 61 { 62 // Prevent infinite loop if user disconnects 63 dataToRead = -1; 64 } 65 } 66 } 67 catch (Exception ex) 68 { 69 // Trap the error, if any. 70 Response.Write("Error : " + ex.Message); 71 } 72 finally 73 { 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