[asp.net]如何利用泛型處理常式(.ashx)來做下載的動作

  • 7564
  • 0
  • 2014-09-03

摘要:[asp.net]如何response.end之後(通常是下載download之後),還能執行後續程式碼,例如javascript alert(),或是code behind額外的程式碼

我自己碰到需要使用泛型處理常式來做下載的動作的情況有兩個:

1.需要按下下載之後,網頁其他的部分還是要能正常運行,不可以就停在那邊,所以必須使用泛型處理常式下載

然後網頁的其他部分才可以繼續正常進行。

2.在update panel 裡面有下載的按鈕,但是update panel裡面是無法利用傳統的下載動作去下載的

因為update panel是非同步回傳資料,所以必須使用泛型處理常式才能下載

 

首先新增一個泛型處理常式filedownload.ashx, 把要下載的指令放在這

vb版本:

Imports System.Web
Imports System.Web.Services

Public Class filedownload
    Implements System.Web.IHttpHandler

    Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest

        'context.context.Response.ContentType = "text/plain"
        'context.context.Response.Write("Hello World!")
        context.Response.ContentType = "application/x-zip-compressed"
        context.Response.AddHeader("Content-Disposition", "attachment; filename=""" & HttpUtility.UrlEncode("testZip.zip", System.Text.Encoding.Default) & """")
        context.Response.Clear()
        context.Response.WriteFile("E:\temp\test.zip")
        context.Response.Flush()
        context.Response.Close()
        context.Response.End()

    End Sub

    ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
        Get
            Return False
        End Get
    End Property

End Class

C#版本:

using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Web;
using System.Web.Services;

public class filedownload : System.Web.IHttpHandler
{


	public void ProcessRequest(HttpContext context)
	{
		//context.context.Response.ContentType = "text/plain"
		//context.context.Response.Write("Hello World!")
		context.Response.ContentType = "application/x-zip-compressed";
		context.Response.AddHeader("Content-Disposition", "attachment; filename=\"" + HttpUtility.UrlEncode("testZip.zip", System.Text.Encoding.Default) + "\"");
		context.Response.Clear();
		context.Response.WriteFile("E:\\temp\\test.zip");
		context.Response.Flush();
		context.Response.Close();
		context.Response.End();

	}

	public bool IsReusable {
		get { return false; }
	}

}

在aspx端增加一個iframe如下

 <iframe id="dlframe" runat="server" style="display: none"></iframe>

設定下載的按鈕的codebehind的指令如下,按下去之後,將會由ashx進行下載的動作,同時response.write也可以執行,讚喔!!

Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        dlframe.Attributes.Add("src", "filedownload.ashx")
        Response.Write(DateTime.Now.ToString())

    End Sub

以上資料來源

http://mobile.dotblogs.com.tw/ian/archive/2012/07/31/73727.aspx

補充:要傳遞參數到.ashx的話,可以用類似如.ashx?abc=123&cde=456這個request的方式之外

如果想要用session的方式傳遞參數,就要在泛型處理常式加上實作喔,如下,其實是多加上

System.Web.SessionState.IRequiresSessionState而已

public class My_Download : IHttpHandler, System.Web.SessionState.IRequiresSessionState

以上資訊來自

[ASP.NET] 如何於泛型處理常式(ashx)中存取工作階段變數(Session)