利用ashx傳送檔案下載

在 asp.net 中, 若要實現檔案下載處理的方式(並且要進行 url 隱藏及下載管理), 可以利用 ashx (generic handler) 來進行, 方式很單純, 主要是在 header 上下一些手腳, 方式如下:

<%@ WebHandler Language="C#" Class="file" %>

using System;
using System.Web;

public class file : IHttpHandler {
    
    public void ProcessRequest (HttpContext context) {
        //context.Response.ContentType = "text/plain";
        //context.Response.Write("Hello World");
        //context.Response.ContentType = "image/png";
        //context.Response.TransmitFile("images/m2.png");        
        context.Response.ContentType = "application/octet-stream";
        context.Response.AppendHeader("Content-Disposition", "attachment; filename=test.doc");
        context.Response.TransmitFile("files/test.doc");        
        
    }
 
    public bool IsReusable {
        get {
            return false;
        }
    }

}

使用的方式若是處理檔案下載, 可以利用 application/octet-stream 這個 ContentType header , 並配合 Content-Disposition header 中, 利用 attachment; filename=xxxx 的方式來將檔案名稱指定給客戶端, 參考資料: http://support.microsoft.com/?scid=kb%3Ben-us%3B260519

而之後再利用 TransmitFile() 方法, 將在 server 上的檔案讀取出來並傳送到客戶端, 至於使用 TransmitFile 方法和其他方法的比較如這篇文章所示: http://blog.miniasp.com/post/2008/03/Caution-about-ASPNET-Response-a-Large-File.aspx

一般來說, 若是大檔案, 可以直接利用 TransmitFile 的方式來進行, 但不是太大型檔案, 有續傳需求時, 則不適用, 但效率上是以 TransmitFile 的效率最佳(因為不用先整個讀到記憶體中).

其他人的比較資料:
[ASP.NET] 無網址的檔案下載 – 進階研究 http://gogo1119.pixnet.net/blog/post/27407222

[2010/2/12 14:48]
相關文章: http://edu.uuu.com.tw/data_article/article/100212tips.htm

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *