locked
Send file to client without blocking(async??) RRS feed

  • Question

  • User1070752316 posted

    Im using the following code to download a file to the clent. Problem is that in the case of large files which take a long time to download the application is blocked while the file is downloading ie not other pages can be loaded. Is there a way to overcome this?

    Private Sub DownloadFile(ByVal downloadasfilename As String, ByVal filepath As String, ByVal contentType As String)
            Dim iStream As Stream = Nothing
            Dim buffer As Byte() = New Byte(1048575) {}
            Dim length As Integer
            Dim dataToRead As Long
         

            Try
                iStream = New FileStream(filepath, FileMode.Open, FileAccess.Read, FileShare.Read)
                dataToRead = iStream.Length
                HttpContext.Current.Response.ContentType = contentType
                HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" & HttpUtility.UrlEncode(downloadasfilename, System.Text.Encoding.UTF8))

                While dataToRead > 0

                    If HttpContext.Current.Response.IsClientConnected Then
                        length = iStream.Read(buffer, 0, 10000)
                        HttpContext.Current.Response.OutputStream.Write(buffer, 0, length)
                        HttpContext.Current.Response.Flush()
                        buffer = New Byte(9999) {}
                        dataToRead = dataToRead - length
                    Else
                        dataToRead = -1
                    End If
                End While
            Catch ex As Exception
                HttpContext.Current.Response.ContentType = "text/html"
                HttpContext.Current.Response.Write("Error : file not found")
            Finally

                If iStream IsNot Nothing Then
                    iStream.Close()
                End If
                File.Delete(filepath)
                HttpContext.Current.Response.[End]()
                HttpContext.Current.Response.Close()
            End Try
        End Sub

    Friday, May 28, 2021 8:50 AM

All replies