首先在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"