Silverlight文件下载完美版

本文详细介绍了如何使用C#编程语言实现一个文件下载服务,包括从客户端获取文件名,构建完整路径,并通过HTTP响应将文件以流的形式发送给客户端。

页面:hlink.NavigateUri = new Uri(ServiceHelper.BaseUrl + ServicePath.DownFilePath + "?fileName="+((Sys_AttachmentLibraryModel)selDownFile.SelectedItem).FileUrl.ToString());


服务端:DownLoadFileHandler.ashx

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

public class DownLoadFileHandler : BaseService
{

    public override void ProcessRequest(HttpContext context)
    {
        Context = context;
        Result = new ActionResult();

        String fileName = context.Request.QueryString["fileName"]; //客户端保存的文件名 
        fileName = HttpUtility.UrlDecode(fileName);
        String filePath = ConfigHelper.UploadPath+ 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.Substring(fileName.LastIndexOf("\\")+1), 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();
        } 

        // 输出结果
        OutputResult();
    }

}



评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值