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

來源:互聯網
上載者:User
asp.net|用戶端 通常的檔案下載是用跳出視窗實現的,但是有個問題,就是會被廣告攔截軟體直接攔截掉,另我非常的頭痛,於是尋找更好的解決方案.看了用Response.BinaryWrite寫檔案流一文之後覺得確實可以如此。
    如下代碼實現了此功能,解決了檔案格式問題(就是只將流輸出,但無法正確識別檔案格式),並且從註冊表讀取檔案的ContentType

1 /**//// <summary>
2 /// 下載檔案
3 /// </summary>
4 /// <param name="filename">檔案物理地址</param>
5 protected void DownloadFile(string filename)
6 {
7
8 string saveFileName = "test.xls";
9 int intStart = filename.LastIndexOf("\\")+1;
10 saveFileName = filename.Substring(intStart,filename.Length-intStart);
11
12 System.IO.FileInfo fi=new System.IO.FileInfo(filename);
13 string fileextname=fi.Extension;
14 string DEFAULT_CONTENT_TYPE = "application/unknown";
15 RegistryKey regkey,fileextkey;
16 string filecontenttype;
17 try
18 {
19 regkey=Registry.ClassesRoot;
20 fileextkey=regkey.OpenSubKey(fileextname);
21 filecontenttype=fileextkey.GetValue("Content Type",DEFAULT_CONTENT_TYPE).ToString();
22 }
23 catch
24 {
25 filecontenttype=DEFAULT_CONTENT_TYPE;
26 }
27
28
29 Response.Clear();
30 Response.Charset = "utf-8";
31 Response.Buffer= true;
32 this.EnableViewState = false;
33 Response.ContentEncoding = System.Text.Encoding.UTF8;
34
35 Response.AppendHeader("Content-Disposition","attachment;filename=" + saveFileName);
36 Response.ContentType=filecontenttype;
37
38 Response.WriteFile(filename);
39 Response.Flush();
40 Response.Close();
41
42 Response.End();
43 }

效果圖如下:

 


相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.