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"
總結
以上是生活随笔為你收集整理的Silverlight实现文件下载的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 医疗:LIS(2)
- 下一篇: Http协议(6)—安全HTTP