ASP.NET 使用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) {
//处理程序的位置,以及要传递给它的查询字符串
var url = "..\\_Handlers\\AttachmentDownload.ashx?";
url = url + "id=" + fileId;
//打开处理程序将运行其代码,它将自动关闭
//完成时。
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会将文件发送到浏览器,并询问用户是否要下载文件。