Silverlight实现文件下载

首先在service层建一个Handler,内容如下:

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;

namespace test.Service
{
       public class WebClientDownHandler : IHttpHandler
    {
      

 
        public void ProcessRequest(HttpContext context)
        {

            String fileName = context.Request.QueryString["filename"]; //客户端保存的文件名
            String filePath = context.Server.MapPath("Pics/" + fileName); //路径

            //string fileName = "ChartImg.png.jpg";

            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();

            }

        
        }

 


        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }

}
假如我们的service的Pics目录下有一个文件test.doc

我们可以试试http://localhost/WebClientDownHandler.ashx?filename=test.doc 看看能不能访问下载文件

 

 

如果成功了,在Silverlight页面直接给HyperlinkButton指定NavigateUri为上述url就可以了,注意可能需要给HyperlinkButton加上TargetName="_self"

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值