捕获响应流并输出到文件

时间:2015-11-09 18:34:26

标签: asp.net vb.net

我们正在使用在线pdf编码服务,我们向他们发送原始html并返回pdf文档。我们想要获取WebResponse并立即将其作为文件下载到他们的桌面。这似乎很简单,但我似乎无法正确捕获流下载。我尝试了很多不同的方法,但总是最终得到一个0字节的文件供下载。这是我最近的化身,它变得过于复杂,但仍然无效。

 Dim request = DirectCast(HttpWebRequest.Create(Url), HttpWebRequest)
    request.Method = "POST"
    request.ContentType = "application/x-www-form-urlencoded"
    request.ContentLength = byteArray.Length
    Using dataStream = request.GetRequestStream()
        dataStream.Write(byteArray, 0, byteArray.Length)
    End Using

    Try
        Dim response As WebResponse = request.GetResponse
        Dim bytes As Byte()
        Using st As Stream = response.GetResponseStream
            Dim ByteList As New ArrayList
            Dim reader As New BinaryReader(st)
            Dim length As Integer

            While (InlineAssignHelper(bytes, reader.ReadBytes(1024))).Length > 0
                ByteList.Add(bytes)
                length += bytes.Length
                bytes = New Byte(length - 1) {}
                Dim position As Integer = 0
                For Each b As Byte() In ByteList
                    Array.Copy(b, 0, bytes, position, b.Length)
                    position += b.Length
                Next
            End While
        End Using
        HttpContext.Current.Response.Clear()
        HttpContext.Current.Response.AddHeader("Content-Type", "application/pdf")
        HttpContext.Current.Response.AddHeader("Content-Disposition", String.Format("{0}; filename=Report Detail.pdf; size={1}", "attachment", bytes.Length.ToString()))
        HttpContext.Current.Response.BinaryWrite(bytes)
        HttpContext.Current.Response.Flush()
        HttpContext.Current.Response.Close()
        HttpContext.Current.Response.End()
 Private Shared Function InlineAssignHelper(Of T)(ByRef target As T, ByVal value As T) As T
    target = value
    Return value
End Function

0 个答案:

没有答案