iT邦幫忙

DAY 16
2

給學弟的ASP.NET網頁學習經驗系列 第 16

ASP.NET學習經驗#16----.ashx泛型處理常式與檔案下載

.ashx是甚麼?

泛型處理常式又是甚麼意思?

HTTP 處理常式和 HTTP 模組概觀

簡單來說

.ashx就是沒有UI介面的網頁,但是進行商業邏輯運作並回應結果!

今天就用檔案下載的功能實作來好好體會一下

首先在製作一個範例的檔案資料表與簡單GridView展示的網頁

撈出基本資訊後再加上一個TemplateField用來放置Link下載檔案用!

並在編輯樣板內放入一個HyperLink並替它做DataBinding

protected void HyperLink1_DataBinding(object sender, EventArgs e)
{
    HyperLink link = (HyperLink)sender;//取得當前觸發這個事件的Hyperlink做連繫
    link.Text = Eval("FileName").ToString();
    link.NavigateUrl = "filedownload.ashx?id=" + Eval("ID");//傳遞ID給ashx處理
}

再來就是加入重頭戲的filedownload.ashx

可以發現它空空如也,沒有設計畫面只有ProcessRequest這個主要運行的功能

接著寫上處理檔案下載的功能:

首先是前置作業取得真正的檔案位置與要使用的檔案名稱

string fileName;
string filaPath;
using (SqlConnection nowConnection = new SqlConnection(strConnection))//使用連接字串初始SqlConnection物件連接資料庫
{
    nowConnection.Open();//開啟連線
    using (SqlCommand command = new SqlCommand())
    {

        command.Parameters.Clear();//清空參數
        command.Parameters.Add("@id", SqlDbType.Int).Value = id;
        command.CommandText = @"select * from Attachment where AttachmentID = @id";
        command.Connection = nowConnection;//資料庫連接
        SqlDataReader dr = command.ExecuteReader();
        dr.Read();
        fileName = dr["AttachmentName"].ToString();
        filaPath = dr["AttachmentPath"].ToString();
    }
}
if(!Download(filaPath, fileName))
{
                context.Response.Expires = 0;
                context.Response.Clear();
                context.Response.ContentType = "text/html";
                context.Response.Write("無檔案");
                context.Response.End();

}

在進行檔案寫入與回傳(示範WriteFile,但寫法不只一種,還有**BinaryWrite、TransmitFile**)

public bool Download(string filePath, string fileName)
//xFile 路徑+檔案, 設定另存的檔名
{
    if (File.Exists(filePath))//檢查檔案是否存在
    {
        try
        {
            FileInfo xpath_file = new FileInfo(filePath);  //要 using System.IO;
            // 將傳入的檔名以 FileInfo 來進行解析(只以字串無法做)
            System.Web.HttpContext.Current.Response.Clear(); //清除buffer
            System.Web.HttpContext.Current.Response.ClearHeaders(); //清除 buffer 表頭
            System.Web.HttpContext.Current.Response.Buffer = false;
            System.Web.HttpContext.Current.Response.ContentType = "application/octet-stream";
            // 檔案類型還有下列幾種"application/pdf"、"application/vnd.ms-excel"
            //、"text/xml"、"text/HTML"、"image/JPEG"、"image/GIF"
            System.Web.HttpContext.Current.Response.AppendHeader("Content-Disposition",
            "attachment;filename=" + System.Web.HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));
            // 考慮 utf-8 檔名問題,以 out_file 設定另存的檔名
            System.Web.HttpContext.Current.Response.AppendHeader("Content-Length", xpath_file.Length.ToString()); //表頭加入檔案大小
            System.Web.HttpContext.Current.Response.WriteFile(xpath_file.FullName);

            // 將檔案輸出
            System.Web.HttpContext.Current.Response.Flush();
            // 強制 Flush buffer 內容
            System.Web.HttpContext.Current.Response.End();
            return true;
        }
        catch (Exception)
        { return false; }

    }
    else
        return false;
}

這樣就可以完成下載囉!!!!!


上一篇
ASP.NET學習經驗#15----基本功Cookie與Session
下一篇
ASP.NET學習經驗#17----Calendar有個日曆也不錯
系列文
給學弟的ASP.NET網頁學習經驗30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 則留言

0
mis2000lab
iT邦好手 1 級 ‧ 2014-10-03 14:52:37

HyperLink1_DataBinding

哇!您在這個事件裡面的作法,我沒想到過

學習了,謝謝您 :-)

我是在畫面上,設定在「樣板」裡面
http://www.dotblogs.com.tw/mis2000lab/archive/2013/08/20/ashx_beginner_03_db_picture_show.aspx

抱歉,PO錯網址

[.ashx檔?泛型處理常式?]基礎入門#5....ADO.NET 與 將DB裡面的二進位圖片還原 (範例下載 & 大型控制項的ImageField)

應該是 http://www.dotblogs.com.tw/mis2000lab/archive/2014/05/19/ashx_beginner_05_db_picture_show_download.aspx

Ben iT邦新手 3 級 ‧ 2014-10-04 16:56:37 檢舉

我也是才剛發現且學習這樣的處理方式!
原本也都是學前輩方式設定在原始碼的樣板上。

過獎過獎我才要多跟您學習!!!!

我要留言

立即登入留言