sivelrlight 結合asp.net用於大文件下載

一、在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;
        }  



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章