使用 httpHandler(.ashx) 從特定位置下載檔案
在 ASP.NET 專案中建立一個新的 httpHandler。將以下程式碼(VB)應用於處理程式檔案:
Public Class AttachmentDownload
Implements System.Web.IHttpHandler
Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
' pass an ID through the query string to append a unique identifer to your downloadable fileName
Dim fileUniqueId As Integer = CInt(context.Request.QueryString("id"))
' file path could also be something like "C:\FolderName\FilesForUserToDownload
Dim filePath As String = "\\ServerName\FolderName\FilesForUserToDownload"
Dim fileName As String = "UserWillDownloadThisFile_" & fileUniqueId
Dim fullFilePath = filePath & "\" & fileName
Dim byteArray() As Byte = File.ReadAllBytes(fullFilePath)
' promt the user to download the file
context.Response.Clear()
context.Response.ContentType = "application/x-please-download-me" ' "application/x-unknown"
context.Response.AppendHeader("Content-Disposition", "attachment; filename=" & fileName)
context.Response.BinaryWrite(byteArray)
context.Response.Flush()
context.Response.Close()
byteArray = Nothing
End Sub
ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
Get
Return False
End Get
End Property
End Class
你可以從後面的程式碼或客戶端語言呼叫處理程式。在這個例子中,我使用的是一個呼叫處理程式的 javascript。
function openAttachmentDownloadHandler(fileId) {
// the location of your handler, and query strings to be passed to it
var url = "..\\_Handlers\\AttachmentDownload.ashx?";
url = url + "id=" + fileId;
// opening the handler will run its code, and it will close automatically
// when it is finished.
window.open(url);
}
現在附加將 javascript 函式分配給 Web 表單中可單擊元素上的按鈕單擊事件。例如:
<asp:LinkButton ID="lbtnDownloadFile" runat="server" OnClientClick="openAttachmentDownloadHandler(20);">Download A File</asp:LinkButton>
或者你也可以從後面的程式碼中呼叫 javascript 函式:
ScriptManager.RegisterStartupScript(Page,
Page.GetType(),
"openAttachmentDownloadHandler",
"openAttachmentDownloadHandler(" & fileId & ");",
True)
現在,當你單擊按鈕時,httpHandler 會將你的檔案傳送到瀏覽器並詢問使用者是否要下載它。