Response.BinaryWrite傳送大型檔案

  • 11293
  • 0

Response.BinaryWrite傳送大型檔案

從之前的Mail找到的,有點像Asp時代,Response粉多TR的方式!

Dim iStream As System.IO.Stream

' Buffer to read 10K bytes in chunk:
Dim buffer(10000) As Byte

' Length of the file:
Dim length As Integer

' Total bytes to read:
Dim dataToRead As Long

' Identify the file to download including its path.
Dim filepath As String = "FileDownload\使用手冊.doc"

' Identify the file name.
Dim filename As String = System.IO.Path.GetFileName(filepath)

Try
    ' Open the file.
    iStream = New System.IO.FileStream(filepath, System.IO.FileMode.Open, _
                                           IO.FileAccess.Read, IO.FileShare.Read)

    ' Total bytes to read:
    dataToRead = iStream.Length

    Response.ContentType = "application/octet-stream"
    Response.AddHeader("Content-Disposition", "attachment; filename=" & filename)

    ' Read the bytes.
    While dataToRead > 0
        ' Verify that the client is connected.
        If Response.IsClientConnected Then
            ' Read the data in buffer
            length = iStream.Read(buffer, 0, 10000)

            ' Write the data to the current output stream.
            Response.OutputStream.Write(buffer, 0, length)

            ' Flush the data to the HTML output.
            Response.Flush()

            ReDim buffer(10000) ' Clear the buffer
            dataToRead = dataToRead - length
        Else
            'prevent infinite loop if user disconnects
            dataToRead = -1
        End If
    End While

Catch ex As Exception
    ' Trap the error, if any.
    Response.Write("Error : " & ex.Message)
Finally
    If IsNothing(iStream) = False Then
        ' Close the file.
        iStream.Close()
    End If
End Try

Hi, 

亂馬客Blog已移到了 「亂馬客​ : Re:從零開始的軟體開發生活

請大家繼續支持 ^_^