수색…


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 함수를 할당하십시오. 예 :

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

또는 코드 뒤에서 자바 스크립트 함수를 호출 할 수도 있습니다.

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

이제 버튼을 클릭하면 httpHandler가 파일을 브라우저로 가져 와서 다운로드 할 것인지 묻습니다.



Modified text is an extract of the original Stack Overflow Documentation
아래 라이선스 CC BY-SA 3.0
와 제휴하지 않음 Stack Overflow