SilverLight下載任意檔案技巧

來源:互聯網
上載者:User

xaml採用LinkButton 其NavigateUri屬性連結到服務端下載的ashx文檔

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

 

download.ashx如下

 

Code
 1Imports System.Web
 2Imports System.Web.Services
 3Imports System.Net
 4Public Class downloadClass download
 5    Implements System.Web.IHttpHandler
 6
 7    Private ChunkSize As Long = 102400 '100K 每次讀取檔案,唯讀取100K,這樣可以緩解伺服器的壓力
 8
 9    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
44    ReadOnly Property IsReusable()Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
45        Get
46            Return False
47        End Get
48    End Property
49
50End Class

聯繫我們

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