在我們的系統的編寫過程中,應該有很多的時候需要客戶下載文件.我第一次的做法(應該也是大部分人的做法吧?)是:
1 HttpResponse response = HttpContext.Current.Response;
2 string js = "<script language=javascript>window.open('{0}');</script>";
3 js = string.Format(js, url);
4 response.Write(js);
5
但是有個問題了,就是會被廣告攔截軟件直接攔截掉,另我非常的頭痛,於是尋找更好的解決方法.看了用Response.BinaryWrite寫文件流一文之後覺得確實可以如此,修改代碼如下:
1/**//**//**//// <summary>
2 /**//// 下載文件
3 /**//// </summary>
4 /**//// <param name="filename">文件物理地址</param>
5
6protected void DownloadFile(string filename)
7 ...{
8 string saveFileName = "test.xls";
9 int intStart = filename.LastIndexOf("\\")+1;
10 saveFileName = filename.Substring(intStart,filename.Length-intStart);
11 FileStream MyFileStream;
12 long FileSize;
13
14 MyFileStream = new FileStream(filename,FileMode.Open);
15 FileSize = MyFileStream.Length;
16
17 byte[] Buffer = new byte[(int)FileSize];
18 MyFileStream.Read(Buffer, 0, (int)FileSize);
19 MyFileStream.Close();
20
21 Response.AddHeader("Content-Disposition", "attachment;filename="+saveFileName);
22 Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
23 Response.ContentType = "application/vnd.ms-excel";
24
25 Response.BinaryWrite(Buffer);
26 Response.Flush();
27 Response.Close();
28 Response.End();
29
30 }