Asp.net直接保存文件到客戶端

     通常的文件下載是用跳出窗口實現的,但是有個問題,就是會被廣告攔截軟件直接攔截掉,另我非常的頭痛,於是尋找更好的解決方法.看了用Response.BinaryWrite寫文件流一文之後覺得確實可以如此。 如下代碼實現了此功能,解決了文件格式問題(就是隻將流輸出,但無法正確識別文件格式),並且從註冊表讀取文件的ContentType 。

 1 ''' <summary>
2 ''' 下載文件
3 ''' </summary>
4 ''' <param name="filename">文件物理地址</param>
5 Protected  Sub DownloadFile(ByVal filename As String)
6
7Dim saveFileName As String =  "test.xls"
8Dim intStart As Integer =  filename.LastIndexOf("//")+1
9 saveFileName = filename.Substring(intStart,filename.Length-intStart)
10
11Dim fi As System.IO.FileInfo = New System.IO.FileInfo(filename)
12Dim fileextname As String = fi.Extension
13Dim DEFAULT_CONTENT_TYPE As String =  "application/unknown"
14Dim regkey As RegisTryKey,fileextkey As RegisTryKey
15Dim filecontenttype As String
16Try
17 regkey=RegisTry.ClassesRoot
18 fileextkey=regkey.OpenSubKey(fileextname)
19 filecontenttype=fileextkey.GetValue("Content Type",DEFAULT_CONTENT_TYPE).ToString()
20Catch
21 filecontenttype=DEFAULT_CONTENT_TYPE
22End Try
23
24
25 Response.Clear()
26 Response.Charset = "utf-8"
27 Response.Buffer= True
28Me.EnableViewState = False
29 Response.ContentEncoding = System.Text.Encoding.UTF8
30
31 Response.AppendHeader("Content-Disposition","attachment;filename=" + saveFileName)
32 Response.ContentType=filecontenttype
33
34 Response.WriteFile(filename)
35 Response.Flush()
36 Response.Close()
37
38 Response.End()
39End Sub

<script type=text/javascript> var arrBaiduCproConfig=new Array(); arrBaiduCproConfig['uid'] =327977; arrBaiduCproConfig['n'] ='web3_cpr'; arrBaiduCproConfig['tm'] ='22'; arrBaiduCproConfig['cm'] ='72'; arrBaiduCproConfig['um'] ='22'; arrBaiduCproConfig['w'] ='728'; arrBaiduCproConfig['h'] ='90'; arrBaiduCproConfig['wn'] ='4'; arrBaiduCproConfig['hn'] ='1'; arrBaiduCproConfig['ta'] ='right'; arrBaiduCproConfig['tl'] ='bottom'; arrBaiduCproConfig['bu'] ='0'; arrBaiduCproConfig['bd'] ='#trans'; arrBaiduCproConfig['bg'] ='#trans'; arrBaiduCproConfig['tt'] ='#0000ff'; arrBaiduCproConfig['ct'] ='#444444'; arrBaiduCproConfig['url'] ='#008000'; arrBaiduCproConfig['bdl'] ='#000000'; arrBaiduCproConfig['rad'] =1; </script> <script src="踢西工作室--Asp_net直接保存文件到客戶端.files/ui.js" type=text/javascript charset=gbk> </script> <script type=text/javascript> </script>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章