SilverLight下载任意文件技巧

xaml采用LinkButton 其NavigateUri属性链接到服务端下载的ashx文档

<HyperlinkButton Margin="32,135,198,140" Content="HyperlinkButton" NavigateUri="http://localhost:1399/download.ashx" />

 

download.ashx如下

 

ContractedBlock.gif ExpandedBlockStart.gif Code
 1Imports System.Web
 2Imports System.Web.Services
 3Imports System.Net
 4ExpandedBlockStart.gifContractedBlock.gifPublic Class downloadClass download
 5    Implements System.Web.IHttpHandler
 6
 7    Private ChunkSize As Long = 102400 '100K 每次读取文件,只读取100K,这样可以缓解服务器的压力
 8
 9ExpandedSubBlockStart.gifContractedSubBlock.gif    Sub ProcessRequest()Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
10        Dim fileName As String = "aaa.JPG" '客户端保存的文件名
11        Dim filePath As String = context.Server.MapPath("image/IMG_1370.JPG"'路径
12
13        Dim fileInfo As System.IO.FileInfo = New System.IO.FileInfo(filePath)
14
15        If fileInfo.Exists = True Then
16
17            Dim buffer(ChunkSize) As Byte
18
19            context.Response.Clear()
20            Dim iStream As System.IO.FileStream = System.IO.File.OpenRead(filePath)
21            Dim 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:
28            While dataLengthToRead > 0 And context.Response.IsClientConnected
29                Dim 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
33            End While
34  
35            context.Response.Close()
36            context.Response.End()
37        End If
38
39        'context.Response.ContentType = "text/plain"
40        'context.Response.Write("Hello World!")
41
42    End Sub

43
44ExpandedSubBlockStart.gifContractedSubBlock.gif    ReadOnly Property IsReusable()Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
45        Get
46            Return False
47        End Get
48    End Property

49
50End Class

转载于:https://www.cnblogs.com/wmt1708/archive/2009/03/07/1405009.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值