Asp.net 下载大文件
Response.WriteFile致命的局限性。WriteFile 在获取文件的路径后,会试图将文件流全部读入内存,之后再发送回客户端。对于小文件和流量很小的网站,使用这个方法或许问题不大,但如果文件很大或者网站的流量很大,使用这个方法可以让 aspnet_wp.exe 进程意味终止,导致当前服务器下所有 asp.net 站点全部瘫痪,不仅如此,服务器的物理内存也会在瞬间被填满,导致其它程序运行失败或意外终止,使用下面代码可解决问题:
View Code
1 System.IO.Stream iStream = null;
2
3 // Buffer to read 10K bytes in chunk:
4 byte[] buffer = new Byte[10000];
5
6 // Length of the file:
7 int length;
8
9 // Total bytes to read:
10 long dataToRead;
11
12 // Identify the file to download including its path.
13 string filepath = "DownloadFileName";
14
15 // Identify the file name.
16 string filename = System.IO.Path.GetFileName(filepath);
17
18 try {
19 // Open the file.
20 iStream = new System.IO.FileStream(filepath, System.IO.FileMode.Open,
21 System.IO.FileAccess.Read, System.IO.FileShare.Read);
22
23
24 // Total bytes to read:
25 dataToRead = iStream.Length;
26
27 Response.ContentType = "application/octet-stream";
28 Response.AddHeader("Content-Disposition", "attachment; filename=" + filename);
29
30 // Read the bytes.
31 while (dataToRead > 0) {
32 // Verify that the client is connected.
33 if (Response.IsClientConnected) {
34 // Read the data in buffer.
35 length = iStream.Read(buffer, 0, 10000);
36
37 // Write the data to the current output stream.
38 Response.OutputStream.Write(buffer, 0, length);
39
40 // Flush the data to the HTML output.
41 Response.Flush();
42
43 buffer = new Byte[10000];
44 dataToRead = dataToRead - length;
45 } else {
46 //prevent infinite loop if user disconnects
47 dataToRead = -1;
48 }
49 }
50 } catch (Exception ex) {
51 // Trap the error, if any.
52 Response.Write("Error : " + ex.Message);
53 } finally {
54 if (iStream != null) {
55 //Close the file.
56 iStream.Close();
57 }
58 }