现在的位置: 首页 > 综合 > 正文

Silverlight实现文件的下载[很简单]

2013年07月14日 ⁄ 综合 ⁄ 共 1605字 ⁄ 字号 评论关闭

思路:使用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:

四.运行效果.


抱歉!评论已关闭.