sivelrlight 结合asp.net用于大文件下载

本文介绍了一种在ASP.NET Web应用程序中实现文件下载的方法。通过创建一个自定义的HTTP处理程序来分块读取文件并发送到客户端,有效减轻了服务器压力。同时展示了如何在页面上设置下载按钮及其点击事件。
摘要由CSDN通过智能技术生成

一、在web项目下添加一个“一般处理程序”

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

namespace Silverlightdownload.Web
{
    /// <summary>
    /// FileDownLoader 的摘要说明
    /// </summary>
    public class FileDownLoader : IHttpHandler
    {
        private long ChunkSize = 20;//100K 每次读取文件,只读取100K,这样可以缓解服务器的压力
        public void ProcessRequest(HttpContext context)
        {
       

            // String fileName = context.Request.QueryString["fileName"]; //客户端传来的文件名  
            //String filePath = context.Server.MapPath("Files/" + fileName); //要下载文件的路径   
            String filePath = context.Request.QueryString["filePath"];
            String fileName = filePath.Substring(filePath.LastIndexOf('/') + 1);

            System.IO.Stream iStream = null;
            byte[] buffer = new byte[ChunkSize]; // Buffer to read 10K bytes in chunk:
            int lengthRead;//读取的大小
            long dataLengthToRead;//获得下载文件的总大小
            context.Response.Clear();
            System.IO.FileInfo fileInfo = new System.IO.FileInfo(filePath);
               
                   
                if (fileInfo.Exists == true)
                {   
                        try
                    {
                    iStream = System.IO.File.OpenRead(filePath);
                        dataLengthToRead = iStream.Length;
                    context.Response.ContentType = "application/octet-stream";
                    //通知浏览器下载文件而不是打开
                    context.Response.AddHeader("Content-Disposition", "attachment;  filename=" + fileName);
                    UserLog.WriteErrLog("dataLengthToRead", dataLengthToRead.ToString());
                       
                    while (dataLengthToRead > 0 && context.Response.IsClientConnected)
                     {
                        if (context.Response.IsClientConnected)
                        {
                                lengthRead = iStream.Read(buffer, 0, Convert.ToInt32(ChunkSize));
                            context.Response.OutputStream.Write(buffer, 0, lengthRead);
                            context.Response.Flush();
                            dataLengthToRead = dataLengthToRead - lengthRead;
                            UserLog.WriteErrLog("dataLengthToRead", dataLengthToRead.ToString());
                        }
                        else {
                            dataLengthToRead = -1;
                        }
                           
                    }
                  }
                 catch (Exception ex)
                        {
                            UserLog.WriteErrLog("LocalDownloadError", ex.ToString());
                            return;
                        }
                 finally
                       {
                            if (iStream != null)
                            {
                                //Close the file.
                                iStream.Close();
                            }
                        }

                   context.Response.Clear();//注意是clear(),不是close(),close()对空文件报错
                   context.Response.End();
            }
               
        }
       


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

二、在页面中添加一个HyperlinkButton控件

<UserControl x:Class="Silverlightdownload.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    d:DesignHeight="300" d:DesignWidth="400">

    <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" Cursor="Hand"/>
    </Grid>
</UserControl>

三、添加点击事件

  private void hyLinkDownLoad_Click(object sender, RoutedEventArgs e)
        {
            string fileName = "C:\\Users\\dell\\Desktop\\ceshi\\hudd1.txt";//要下载的文件名  
            Uri uri = new Uri("/FileDownLoader.ashx?filePath=" + fileName, UriKind.Relative);
            this.hyLinkDownLoad.NavigateUri = uri;
        }  



评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值