Zoeken…


Een httpHandler (.ashx) gebruiken om een bestand van een specifieke locatie te downloaden

Maak een nieuwe httpHandler binnen uw ASP.NET-project. Pas de volgende code (VB) toe op het handlerbestand:

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

U kunt de handler oproepen vanuit de code achter of vanuit een taal aan de clientzijde. In dit voorbeeld gebruik ik een javascript die de handler aanroept.

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);

} 

Voeg nu toe die de javascript-functie toewijst aan een knopklikgebeurtenis op een klikbaar element in uw webformulier. Bijvoorbeeld:

<asp:LinkButton ID="lbtnDownloadFile" runat="server" OnClientClick="openAttachmentDownloadHandler(20);">Download A File</asp:LinkButton>

Of u kunt ook de JavaScript-functie oproepen vanuit de code erachter:

ScriptManager.RegisterStartupScript(Page,
                Page.GetType(),
                "openAttachmentDownloadHandler",
                "openAttachmentDownloadHandler(" & fileId & ");",
                True)

Als u nu op uw knop klikt, zal de httpHandler uw bestand naar de browser sturen en de gebruiker vragen of hij het wil downloaden.



Modified text is an extract of the original Stack Overflow Documentation
Licentie onder CC BY-SA 3.0
Niet aangesloten bij Stack Overflow