SilverLight下载任意文件技巧
xaml采用LinkButton 其NavigateUri属性链接到服务端下载的ashx文档 如 HyperlinkButton Margin="32,135,198,140" Content="HyperlinkButton" NavigateUri="http://localhost:1399/download.ashx" / download.ashx 如下 Code 1 Imports System.Web 2 Imports
xaml采用LinkButton 其NavigateUri属性链接到服务端下载的ashx文档
如
download.ashx如下
Code
1Imports System.Web
2Imports System.Web.Services
3Imports System.Net
4Public Class downloadClass download
5Implements System.Web.IHttpHandler
6
7Private ChunkSize As Long = 102400 '100K 每次读取文件,只读取100K,这样可以缓解服务器的压力
8
9Sub ProcessRequest()Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
10Dim fileName As String = "aaa.JPG" '客户端保存的文件名
11 Dim filePath As String = context.Server.MapPath("image/IMG_1370.JPG") '路径
12
13Dim fileInfo As System.IO.FileInfo = New System.IO.FileInfo(filePath)
14
15If fileInfo.Exists = True Then
16
17Dim buffer(ChunkSize) As Byte
18
19 context.Response.Clear()
20Dim iStream As System.IO.FileStream = System.IO.File.OpenRead(filePath)
21Dim dataLengthToRead As Long = iStream.Length '获取下载的文件总大小
22
23 context.Response.ContentType = "application/octet-stream"
24'通知浏览器下载文件而不是打开
25 context.Response.AddHeader("Content-Disposition", "attachment; filename=" & _
26 HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8))
27Loop1:
28While dataLengthToRead > 0 And context.Response.IsClientConnected
29Dim lengthRead As Integer = iStream.Read(buffer, 0, Convert.ToInt32(ChunkSize)) '读取的大小
30 context.Response.OutputStream.Write(buffer, 0, lengthRead)
31 context.Response.Flush()
32 dataLengthToRead = dataLengthToRead - lengthRead
33End While
34
35 context.Response.Close()
36 context.Response.End()
37End If
38
39'context.Response.ContentType = "text/plain"
40 'context.Response.Write("Hello World!")
41
42End Sub
43
44ReadOnly Property IsReusable()Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
45Get
46Return False
47End Get
48End Property
49
50End Class