Silverlight实现文件的下载[很简单]
生活随笔
收集整理的這篇文章主要介紹了
Silverlight实现文件的下载[很简单]
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
思路:使用HyperlinkButton的NavigateUri屬性來(lái)訪問(wèn)ashx程序,來(lái)實(shí)現(xiàn)文件下載。
源碼:點(diǎn)擊下載
一. 新建一個(gè)Silverlight應(yīng)用程序
在web項(xiàng)目所在的目錄下新建名為Files的文件夾,存放提供下載的文件a.txt;
二.在web項(xiàng)目下添加一個(gè)“一般處理程序”
實(shí)現(xiàn)ProcessRequest函數(shù)代碼如下:
public void ProcessRequest(HttpContext context){String fileName = context.Request.QueryString["fileName"]; //客戶端傳來(lái)的文件名String filePath = context.Server.MapPath("Files/" + fileName); //要下載文件的路徑 FileInfo fileInfo = new FileInfo(filePath);if (fileInfo.Exists){byte[] buffer = new byte[102400];context.Response.Clear();FileStream iStream = File.OpenRead(filePath);long dataLengthToRead = iStream.Length; //獲取下載的文件總大小context.Response.ContentType = "application/octet-stream";context.Response.AddHeader("Content-Disposition", "attachment; filename=" +HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));while (dataLengthToRead > 0 && context.Response.IsClientConnected){int lengthRead = iStream.Read(buffer, 0, Convert.ToInt32(102400));//'讀取的大小context.Response.OutputStream.Write(buffer, 0, lengthRead);context.Response.Flush();dataLengthToRead = dataLengthToRead - lengthRead;}context.Response.Close();context.Response.End();}
三.在MainPage頁(yè)面添加一個(gè)HyperlinkButton控件
代碼為:
<Grid x:Name="LayoutRoot" Background="White"><HyperlinkButton Name="hyLinkDownLoad" Content="下載文件" HorizontalAlignment="Left" Height="17" Margin="67,83,0,0" VerticalAlignment="Top" Width="73" Click="hyLinkDownLoad_Click"/></Grid>
按鈕點(diǎn)擊事件函數(shù):
? ? ? ? private void hyLinkDownLoad_Click(object sender, RoutedEventArgs e){string fileName = "a.txt";//要下載的文件名Uri uri = new Uri("http://localhost:9698/FileDownLoader.ashx?fileName=" + fileName);this.hyLinkDownLoad.NavigateUri = uri;}
注意:其中的9698為端口號(hào),每個(gè)程序端口號(hào)不一樣可以在web項(xiàng)目屬性中查看,我的這個(gè)項(xiàng)目為9698:
四.運(yùn)行效果.
總結(jié)
以上是生活随笔為你收集整理的Silverlight实现文件的下载[很简单]的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 计算机b级英语翻译,英语B级考试翻译必备
- 下一篇: 《乔布斯传》摘录