正在閱讀:Asp.net直接保存文件到客戶端Asp.net直接保存文件到客戶端

2005-09-26 10:00 出處: 作者:浪子 責(zé)任編輯:moningfeng

  熱門推薦ASP漏洞解析及黑客防范法    微軟副總裁給中國大學(xué)生的一封信

  在我們的系統(tǒng)的編寫過程中,應(yīng)該有很多的時候需要客戶下載文件.我第一次的做法(應(yīng)該也是大部分人的做法吧?)是:

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 }
31


  但是有個嚴(yán)重的問題,就是文件格式。這樣只是將流輸出,且無法正確識別格式。還好,能人層出不窮, 柚子Nan 提出了能否不考慮文件的類型,直接把文件顯示到瀏覽器(Response) 的想法正好切中我的要害所在,于是急忙研究了柚子Nan的想法,修改出最后代碼:

鍵盤也能翻頁,試試“← →”鍵
302 Found

302 Found


Powered by Tengine
tengine