Silverlight实现文件的下载[很简单]
生活随笔
收集整理的這篇文章主要介紹了
Silverlight实现文件的下载[很简单]
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
思路:使用HyperlinkButton的NavigateUri屬性來訪問ashx程序,來實現文件下載。
源碼:點擊下載
一. 新建一個Silverlight應用程序
在web項目所在的目錄下新建名為Files的文件夾,存放提供下載的文件a.txt;
二.在web項目下添加一個“一般處理程序”
實現ProcessRequest函數代碼如下:
public void ProcessRequest(HttpContext context){String fileName = context.Request.QueryString["fileName"]; //客戶端傳來的文件名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頁面添加一個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>
按鈕點擊事件函數:
? ? ? ? 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為端口號,每個程序端口號不一樣可以在web項目屬性中查看,我的這個項目為9698:
四.運行效果.
總結
以上是生活随笔為你收集整理的Silverlight实现文件的下载[很简单]的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 计算机b级英语翻译,英语B级考试翻译必备
- 下一篇: html 圆球的百分比,HTML5 很酷