ASP.NET利用HttpHandler實現多副檔名檔案下載

iDotNetSpace發表於2009-02-11

以前寫過這樣一篇文章(ASP.NET檔案下載函式(好用的東東)),發現很多朋友詢問,並且有時候會發生錯誤,今天我再重新更新一下,利用IHttpHandler來實現多副檔名檔案下載,思路是這樣:

1. 首先新建一個用於進行下載處理的page頁,如download.aspx,裡面什麼東西也沒有。

2. 新增一個DownloadHandler類,它繼承於IHttpHandler介面,可以用來自定義HTTP 處理程式同步處理HTTP的請求。

public class DownloadHandler : IHttpHandler
{
    public void ProcessRequest(HttpContext context)
    {
        HttpResponse Response = context.Response;
        HttpRequest Request = context.Request;

        System.IO.Stream iStream = null;

        byte[] buffer = new Byte[10240];

        int length;

        long dataToRead;

        try
        {
            string filename = FileHelper.Decrypt(Request["fn"]); //通過解密得到檔名

            string filepath = HttpContext.Current.Server.MapPath("~/") + "files/" + filename; //待下載的檔案路徑

            iStream = new System.IO.FileStream(filepath, System.IO.FileMode.Open,
                System.IO.FileAccess.Read, System.IO.FileShare.Read);
            Response.Clear();

            dataToRead = iStream.Length;

            long p = 0;
            if (Request.Headers["Range"] != null)
            {
                Response.StatusCode = 206;
                p = long.Parse(Request.Headers["Range"].Replace("bytes=", "").Replace("-", ""));
            }
            if (p != 0)
            {
                Response.AddHeader("Content-Range", "bytes " + p.ToString() + "-" + ((long)(dataToRead - 1)).ToString() + "/" + dataToRead.ToString());
            }
            Response.AddHeader("Content-Length", ((long)(dataToRead - p)).ToString());
            Response.ContentType = "application/octet-stream";
            Response.AddHeader("Content-Disposition", "attachment; filename=" + System.Web.HttpUtility.UrlEncode(System.Text.Encoding.GetEncoding(65001).GetBytes(Path.GetFileName(filename))));

            iStream.Position = p;
            dataToRead = dataToRead - p;

            while (dataToRead > 0)
            {
                if (Response.IsClientConnected)
                {
                    length = iStream.Read(buffer, 0, 10240);

                    Response.OutputStream.Write(buffer, 0, length);
                    Response.Flush();

                    buffer = new Byte[10240];
                    dataToRead = dataToRead - length;
                }
                else
                {
                    dataToRead = -1;
                }
            }
        }
        catch (Exception ex)
        {
            Response.Write("Error : " + ex.Message);
        }
        finally
        {
            if (iStream != null)
            {
                iStream.Close();
            }
            Response.End();
        }
    }

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

3. 這裡涉及到一個檔名加解密的問題,是為了防止檔案具體名稱暴露在狀態列中,所以新增一個FileHelper類,程式碼如下:

public class FileHelper
{
    public static string Encrypt(string filename)
    {
        byte[] buffer = HttpContext.Current.Request.ContentEncoding.GetBytes(filename);
        return HttpUtility.UrlEncode(Convert.ToBase64String(buffer));
    }

    public static string Decrypt(string encryptfilename)
    {
        byte[] buffer = Convert.FromBase64String(encryptfilename);
        return HttpContext.Current.Request.ContentEncoding.GetString(buffer);
    }
}
利用Base64碼對檔名進行加解密處理。

4. 在Web.config上,新增httpHandlers結點,如下:


 
 
   
 

5. 現在新建一個aspx頁面,對檔案進行下載:

Default.aspx程式碼如下:

Default.aspx Code

ttp://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

http://www.w3.org/1999/xhtml" >


    檔案下載


   
   

   
   

   


Default.aspx.cs程式碼如下:

Default.aspx.cs Code
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        string url = FileHelper.Encrypt("DesignPattern.chm");
        link.NavigateUrl = "~/download.aspx?fn=" + url;
    }
}
這樣就實現了檔案下載時,不管是什麼格式的檔案,都能夠彈出開啟/儲存視窗。:)


 

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/12639172/viewspace-545679/,如需轉載,請註明出處,否則將追究法律責任。

相關文章