asp.net常用的一個很好用的控制檔案下載的函數 支援續傳多線(控制多線請自行修改)

來源:互聯網
上載者:User

可以控制檔案大小 下載名稱 單塊資料大小 單塊資料間隔 以及MIME類型 很好用


    Public Shared Function ResponseFile()Function ResponseFile(ByVal _Request As HttpRequest, ByVal _Response As HttpResponse, ByVal _fileName As String, ByVal _fullPath As String, ByVal BlockSize As Long, ByVal sleep As Integer, Optional ByVal MIMEType As String = "application/octet-stream") As Boolean
        Try



            Dim myFile As New FileStream(_fullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)

            Dim br As New BinaryReader(myFile)


            Try

                _Response.AddHeader("Accept-Ranges", "bytes")
                _Response.Buffer = False
                Dim fileLength As Long = myFile.Length
                Dim startBytes As Long = 0




                If (Not _Request.Headers("Range") Is Nothing) Then
                    _Response.StatusCode = 206
                    Dim range() As String = _Request.Headers("Range").Split("=-".ToCharArray)
                    startBytes = Convert.ToInt64(range(1))

                End If

                _Response.AddHeader("Content-Length", (fileLength - startBytes).ToString())
                If (startBytes <> 0) Then
                    _Response.AddHeader("Content-Range", String.Format(" bytes {0}-{1}/{2}", startBytes, fileLength - 1, fileLength))

                End If
                _Response.AddHeader("Connection", "Keep-Alive")
                _Response.ContentType = MIMEType
                _Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(_fileName, System.Text.Encoding.UTF8))

                br.BaseStream.Seek(startBytes, SeekOrigin.Begin)
                Dim maxCount As Integer = CInt(Math.Floor((fileLength - startBytes) / BlockSize) + 1)
                For i As Integer = 0 To maxCount - 1

                    If _Response.IsClientConnected Then
                        _Response.BinaryWrite(br.ReadBytes(BlockSize))
                        Thread.Sleep(sleep)

                    Else
                        i = maxCount
                    End If

                Next
            Catch ex As Exception

                Return False
            End Try





        Catch ex As Exception

            Return False

        End Try
    End Function

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.