使用 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 会将你的文件发送到浏览器并询问用户是否要下载它。