使用HttpWebRequest下载将停止网站响应

时间:2019-07-16 19:26:43

标签: asp.net httphandler

我正在尝试通过使用HttpWebRequest掩盖下载来向用户隐藏下载链接。效果很好,但最近我发现下载文件时,无法通过客户端下载访问该网站。该网页一直在加载

除了找到另一种隐藏下载链接的方法外,我不确定这时该怎么做。

Private Sub download_Load(sender As Object, e As EventArgs) Handles Me.Load

        Dim stream As Stream = Nothing
        Dim bytesToRead As Integer = 10000
        Dim buffer As Byte() = New Byte(bytesToRead - 1) {}
        Dim FileURL As String = Session("DownloadURL")
        Dim FileName As String = Session("DownloadName")

        If FileURL = "" Or FileName = "" Then
            Response.Redirect("index")
        End If

        Try
            Dim fileReq As HttpWebRequest = CType(HttpWebRequest.Create(FileURL), HttpWebRequest)
            Dim fileResp As HttpWebResponse = CType(fileReq.GetResponse(), HttpWebResponse)
            If fileReq.ContentLength > 0 Then fileResp.ContentLength = fileReq.ContentLength
            stream = fileResp.GetResponseStream()
            Dim resp = HttpContext.Current.Response
            resp.ContentType = "application/octet-stream"
            resp.AddHeader("Content-Disposition", "attachment; filename=""" & FileName & """")
            resp.AddHeader("Content-Length", fileResp.ContentLength.ToString())
            Dim length As Integer

            Do

                If resp.IsClientConnected Then
                    length = stream.Read(buffer, 0, bytesToRead)
                    resp.OutputStream.Write(buffer, 0, length)
                    resp.Flush()
                    buffer = New Byte(bytesToRead - 1) {}
                Else
                    length = -1
                End If

            Loop While length > 0

        Finally

            If stream IsNot Nothing Then
                stream.Close()
            End If
        End Try

        Session("DownloadURL") = ""
        Session("DownloadName") = ""
    End Sub

在下载过程中尝试访问网站时完全没有错误。它只是一直加载,直到下载完成或取消。

0 个答案:

没有答案