Asp.net直接儲存檔案到用戶端

來源:互聯網
上載者:User

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

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 }

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.