思路:使用HyperlinkButton的NavigateUri属性来访问ashx程序,来实现文件下载。
源码:点击下载
一. 新建一个Silverlight应用程序
在web项目所在的目录下新建名为Files的文件夹,存放提供下载的文件a.txt;
二.在web项目下添加一个“一般处理程序”
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,Convert.ToInt32(102400));//'读取的大小 context.Response.OutputStream.Write(buffer,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" 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:
四.运行效果.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。